sgbj / crontimer Goto Github PK
View Code? Open in Web Editor NEWLike PeriodicTimer but for cron jobs.
License: MIT License
Like PeriodicTimer but for cron jobs.
License: MIT License
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.");
}
}
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);
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.