GithubHelp home page GithubHelp logo

crontimer's Introduction

Sgbj.Cron.CronTimer

Provides a cron timer similar to System.Threading.PeriodicTimer that enables waiting asynchronously for timer ticks.

Available on NuGet.

Usage

Normal usage:

// Every minute
using var timer = new CronTimer("* * * * *");

while (await timer.WaitForNextTickAsync())
{
    // Do work
}

Example hosted service:

public class CronJob : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // Every day at 8am local time
        using var timer = new CronTimer("0 8 * * *", TimeZoneInfo.Local);

        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            // Do work
        }
    }
}

Non-standard cron expression:

// Every 30 seconds
using var timer = new CronTimer(CronExpression.Parse("*/30 * * * * *", CronFormat.IncludeSeconds));

Resources

crontimer's People

Contributors

adamfoneil avatar patrik-hlinka-vissim avatar sgbj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

crontimer's Issues

WaitForNextTickAsync doesn't seem to return during graceful shutdown

I have a cronjob that looks like the following.

When I shutdown the app using Ctrl+C on my laptop, the service does not print the DoSomethingCronJob stopped, it seems like it's still stuck in the loop waiting for the next tick.

I'd expect the loop to break and allow me to perform whatever I need for a safe shutdown

public class DoSomethingCronJob : BackgroundService
{
    private readonly ILogger _logger;

    public DoSomethingCronJob(ILogger<DoSomethingCronJob> logger)
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    protected override async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("DoSomethingCronJob is starting.");

        using var timer = new CronTimer("0 0 * * *", TimeZoneInfo.Utc);

        while (await timer.WaitForNextTickAsync(cancellationToken))
        {
            _logger.LogInformation("doing something");
        }

        _logger.LogInformation("DoSomethingCronJob stopped.");
    }
}

ArgumentNullException from Garbage Collection thread

We are running some BackgroundService workers using either PeriodicTimer or Sgbj.Cron.CronTimer. The problem occurs only when running one specific worker with Sgbj.Cron.CronTimer (no issue with PeriodicTimer).

Using net6.0 and Sgbj.Cron.CronTimer version 1.0.1.

The exception from Garbage Collection thread:

An unhandled exception of type 'System.ArgumentNullException' occurred in System.Private.CoreLib.dllValue cannot be null.
   at System.Threading.Monitor.ReliableEnter(Object obj, Boolean& lockTaken)
   at System.Threading.Monitor.Enter(Object obj, Boolean& lockTaken)
   at Sgbj.Cron.CronTimer.Dispose()
   at Sgbj.Cron.CronTimer.Finalize()

It appears that the more frequent we run the worker, the sooner the exception is thrown.
When running every 10 seconds, it throws after ~90seconds.
When running every 20 seconds, it throws after ~180seconds.

At first we though there is some memory leak or similar issue, but when running the same intervals with PeriodicTimer, there is no issue even after much longer time period. Still, the issue is obviously specific to worker's work. While I cannot share the worker-specific code, it frequently uses Entity Framework and transactions.

Below you can find our abstract implementation of the worker:

using Cronos;
using dashboard_service.Configuration.Workers;
using Sgbj.Cron;

namespace dashboard_service.Workers;

public abstract class BackgroundWorker<TScopedService> : BackgroundService
{
    private readonly IWorkerConfiguration _configuration;
    private readonly ILogger _logger;
    private readonly IServiceScopeFactory _serviceScopeFactory;

    protected BackgroundWorker(IWorkerConfiguration configuration, ILogger logger,
        IServiceScopeFactory serviceScopeFactory)
    {
        _configuration = configuration;
        _logger = logger;
        _serviceScopeFactory = serviceScopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var workerName = GetType().Name;
        if (!_configuration.Enabled)
        {
            _logger.LogInformation("{worker} won't be executed (disabled worker)", workerName);
            return;
        }
        _logger.LogInformation("{worker} will be executed", workerName);

        var isCronExpressionValid = _configuration.IsCronExpressionValid();
        var isFixedDelayValid = _configuration.IsFixedDelayValid();
        if (!(isCronExpressionValid ^ isFixedDelayValid))
        {
            _logger.LogError("Failed to execute {worker} (invalid configuration)", workerName);
            return;
        }

        using var periodicTimer = isFixedDelayValid ? CreatePeriodicTimer() : null;
        using var cronTimer = isCronExpressionValid ? CreateCronTimer() : null;
        using var scope = _serviceScopeFactory.CreateScope();

        while (!stoppingToken.IsCancellationRequested &&
               await WaitForNextTickAsync(periodicTimer, cronTimer, stoppingToken))
        {
            if (periodicTimer != null)
            {
                _logger.LogInformation("Executing {worker} work with fixed delay {interval} seconds",
                    workerName, _configuration.FixedDelaySeconds);
            }
            else
            {
                _logger.LogInformation("Executing {worker} work with '{cron}' cron expression",
                    workerName, _configuration.CronExpression);
            }
            
            var service = scope.ServiceProvider.GetService<TScopedService>();
            if (service == null)
            {
                _logger.LogError("Failed to execute {worker} (scoped service not found)", workerName);
                return;
            }

            try
            {
                await ExecuteWorkAsync(service);
            }
            catch (Exception exception)
            {
                _logger.LogError("Failed to execute {worker} (caught exception: {exception})",
                    workerName, exception);
            }
        }
    }

    private static async ValueTask<bool> WaitForNextTickAsync(PeriodicTimer? periodicTimer, CronTimer? cronTimer,
        CancellationToken stoppingToken)
    {
        return (periodicTimer != null && await periodicTimer.WaitForNextTickAsync(stoppingToken))
               || (cronTimer != null && await cronTimer.WaitForNextTickAsync(stoppingToken));
    }

    private CronTimer CreateCronTimer()
    {
        var timezone = TimeZoneInfo.Utc;
        var cronExpressionValue = _configuration.CronExpression!;
        try
        {
            return new CronTimer(cronExpressionValue, timezone);
        }
        catch (CronFormatException)
        {
            var cronExpression = CronExpression.Parse(cronExpressionValue, CronFormat.IncludeSeconds);
            return new CronTimer(cronExpression, timezone);
        }
    }

    private PeriodicTimer CreatePeriodicTimer()
    {
        return new PeriodicTimer(TimeSpan.FromSeconds(_configuration.FixedDelaySeconds!.Value));
    }

    protected abstract Task ExecuteWorkAsync(TScopedService service);
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.