wangjia184 / HashedWheelTimer

HashedWheelTimer implemented in C# and .Net Standard inspired by io.netty.util.HashedWheelTimer
MIT License
113 stars 16 forks source link

Is it support for cron? #3

Closed zhujiancc closed 3 years ago

zhujiancc commented 3 years ago

I don't know How to implement CronTimerTask with HashedWheelTimer

here is my code :

public class CronTimerTask : TimerTask
{
    private readonly CronExpression cron;
    private readonly string taskName;

    public CronTimerTask(string taskName, CronExpression cron)
    {
        this.cron = cron;
        this.taskName = name;
    }

    public void Run(Timeout timeout)
    {
        var offset = cron.GetNextOccurrence(DateTimeOffset.UtcNow, TimeZoneInfo.Local) ?? new DateTimeOffset();
        timeout.Timer.NewTimeout(new CronRunnerTask(taskName, cron), TimeSpan.FromSeconds(offset.Second));
    }
}

public class CronRunnerTask : TimerTask
{
    private readonly string taskName;
    private readonly CronExpression cron;

    public CronRunnerTask(string taskName, CronExpression cron)
    {
        this.taskName = taskName;
        this.cron = cron;
    }

    public void Run(Timeout timeout)
    {
        timeout.Timer.NewTimeout(new CronTimerTask(taskName, cron), TimeSpan.FromSeconds(0));
        Console.WriteLine($"{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} Run CronRunnerTask{taskName}");
    }
}

The trigger time is not correct , please help me~~

wangjia184 commented 3 years ago
timeout.Timer.NewTimeout(new CronTimerTask(taskName, cron), TimeSpan.FromSeconds(0));

First, for the same cron task, instead of having a new CronTimerTask(taskName, cron) everytime it is triggered, better to reuse the current one.

Second, TimeSpan.FromSeconds(0) should be changed to next offset gotten from cron.GetNextOccurrence(). Note that you may need add some seconds to void cron.GetNextOccurrence() return the current time