Tuesday, May 2, 2023

Sample Windows Service Job Scheduling Application that uses a Cron Expression

Here's an example code in C# for a Windows Service job scheduling application that uses a cron expression.
using System;
using System.ServiceProcess;
using System.Threading.Tasks;
using NCrontab;

namespace CronJobServiceExample
{
    public partial class CronJobService : ServiceBase
    {
        private readonly CrontabSchedule _schedule;
        private DateTime _nextOccurrence;

        public CronJobService()
        {
            InitializeComponent();

            var cronExpression = "0 0 12 * * ?"; // Cron expression for every day at noon
            _schedule = CrontabSchedule.Parse(cronExpression);
            _nextOccurrence = _schedule.GetNextOccurrence(DateTime.Now);
        }

        protected override void OnStart(string[] args)
        {
            Task.Run(() => RunJob());
        }

        protected override void OnStop()
        {
            // Stop job if running
        }

        private async Task RunJob()
        {
            while (true)
            {
                var delay = _nextOccurrence - DateTime.Now;

                if (delay > TimeSpan.Zero)
                {
                    await Task.Delay(delay);
                }

                // Perform job here
                Console.WriteLine("Job executed!");

                _nextOccurrence = _schedule.GetNextOccurrence(DateTime.Now);
            }
        }
    }
}
In this example, the 'cronExpression' variable is set to '"0 0 12 * * ?"', which represents a cron expression for every day at noon. The 'CrontabSchedule' class is used to parse the cron expression and calculate the next occurrence of the scheduled job. The 'RunJob' method is executed continuously in a background thread and waits for the next occurrence of the job using 'Task.Delay'. Once the delay has elapsed, the job is executed and the next occurrence of the job is calculated.

Note that in this example, the job itself is not defined and is represented by the comment '// Perform job here'. You can replace this comment with your own code to execute the job. Also, the 'OnStop' method should be implemented to stop the job if it is running when the service is stopped.

No comments:

Post a Comment