What is Cron Job?
Cron is a program used to repeat a task on a system. A task assignment is a cron job if it does not command a repeat as a whole.
How does a cron job work?
If you want to schedule a task once at a later time, you can use another command like it. But for repetitive tasks, cron is a great solution.
Cron Services
You can write your own CronJob classes using the CronJobService abstract class. We’ve included a sample cron job for you. When this cron job runs, it logs the related job on the console.
First, install the EasyCronJob.Core library on your application via Nuget.
You can now create your own cron jobs.
public class ConsoleCronJob : CronJobService
{
private readonly ILogger<ConsoleCronJob> logger;
public ConsoleCronJob(ICronConfiguration<ConsoleCronJob> cronConfiguration, ILogger<ConsoleCronJob> logger)
: base(cronConfiguration.CronExpression,cronConfiguration.TimeZoneInfo)
{
this.logger = logger;
}
public override Task StartAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Start");
return base.StartAsync(cancellationToken);
}
protected override Task ScheduleJob(CancellationToken cancellationToken)
{
logger.LogInformation("Scheduled");
return base.ScheduleJob(cancellationToken);
}
public override Task DoWork(CancellationToken cancellationToken)
{
logger.LogInformation("Do Work");
return base.DoWork(cancellationToken);
}
}
Startup Configuration
For the cron job you created, you must configure it in Startup.cs.
Do not worry. This configuration is pretty simple.
services.ApplyResulation<ConsoleCronJob>(options =>
{
options.CronExpression = "* * * * *";
options.TimeZoneInfo = TimeZoneInfo.Local;
});
Process completed. Now, your cron job will run when the cron expression value you specified comes.
Crontab.guru
Cron values can be confusing at times. You don’t have to memorize them. You can use the crontab.guru website to generate the cron values you want or to learn the runtime of an existing cron value.
Documentation
Visit Wiki page for documentation.