C# Quartz Jobs (Scheduled Tasks)

Date: 2016-12-16
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Application.Business.Service;
using Application.BusinessObjects;
using log4net;
using Quartz;
using Quartz.Impl;

namespace Application.WindowsService
{
    public class Dispatcher
    {
        private IScheduler scheduler;
        private readonly ScheduledTaskService scheduledTaskService;        
        private readonly ILog log;

        public Dispatcher()
        {
            scheduledTaskService = new ScheduledTaskService();
            log = LogManager.GetLogger(typeof(Dispatcher));
        }

        public async Task InitializeTasksAsync()
        {
            await Task.Run(() =>
            {
                try
                {
                    scheduler = StdSchedulerFactory.GetDefaultScheduler();
                    scheduler.Start();

                    var assembly = Assembly.GetAssembly(typeof(Dispatcher));
                      
                    // Test a specific task                  
                    //TriggerTaskNow<ACustomTask();

                    var windowsserviceTasksScheduletasks = "Application.WindowsService.Tasks.ScheduleTasks";
                    var taskType = assembly.GetType(windowsserviceTasksScheduletasks);

                    if (taskType == null)
                    {
                        var message = string.Format("Task {0} with type {1} cannot be resolved.",
                            windowsserviceTasksScheduletasks, "ScheduleTasks");
                        //console.WriteLine(message);
                        log.Error(message);
                    }
                    else
                    {
                        ScheduleJob(taskType);
                    }

                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            });
        }

        private void ScheduleJob(Type taskType)
        {
            var job = JobBuilder.Create(taskType).WithIdentity("ScheduleTasks").Build();

            var trigger = (ICronTrigger)TriggerBuilder.Create().WithCronSchedule("0 0/1 * * * ?").Build();

            var dateTimeOffset = scheduler.ScheduleJob(job, trigger);

            var message = $"Task {"ScheduleTasks"} is scheduled on {dateTimeOffset} and will repeat using this cron expression: {trigger.CronExpressionString}";

            //console.WriteLine(message);
            log.Info(message);
        }

        public static async void TriggerTaskNow() where T : IJob
        {
            await Task.Run(() =>
            {
                var scheduler = StdSchedulerFactory.GetDefaultScheduler();

                // Controleren of de taak niet nu al draait
                var jobs = scheduler.GetCurrentlyExecutingJobs();
                foreach (var job in jobs)
                {
                    if (job.JobDetail.JobType == typeof(T))
                    {
                        // Job is already running
                        return;
                    }
                }

                var newJob = JobBuilder.Create().Build();
                scheduler.ScheduleJob(newJob, TriggerBuilder.Create().StartNow().Build());
            });
        }

        public void Stop()
        {
            log.Info("Shutdown scheduler.");
            scheduler.Shutdown(true);
        }
    }
}

5400cookie-checkC# Quartz Jobs (Scheduled Tasks)