星期三, 4月 06, 2022

[C#] Quartz.NET - 傳遞自訂 class

[C#] Quartz.NET 筆記中,有紀錄傳遞參數方式,該篇筆記是要透過 JobDataMap 把自訂 class 傳進 Job 去

自訂 class
namespace QuartzSample
{
    public class CustomClass
    {
        public int ID { get; set; }
        public string Description { get; set; }

        public override string ToString()
        {
            return $"編號-{ID} ; 描述:{Description}";
        }
    }
}
Job 內透過 JobDetail 和 JobDataMap 把自訂 class 抓出來
using Quartz;
using System;
using System.Threading.Tasks;

namespace QuartzSample
{
    public class PassCustomClassJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            var customClass = context.JobDetail.JobDataMap[nameof(CustomClass)] as CustomClass;

            return Task.Run(() => {
                Console.WriteLine(customClass.ToString());
            });
        }
    }
}

測試 Code
namespace QuartzSample
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            StdSchedulerFactory factory = new StdSchedulerFactory();
            IScheduler scheduler = await factory.GetScheduler();
            await scheduler.Start();
            
            // 透過 JobDataMap 把自訂 class 傳進 Job 內
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.Add(nameof(CustomClass), new CustomClass() { ID = 1 , Description = "傳遞自訂 class"});

            IJobDetail job = JobBuilder.Create<PassCustomClassJob>()
                .UsingJobData(jobDataMap) // 把自訂 class 傳進 Job 內
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .StartNow()
                .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(1) 
                    .RepeatForever())
                .Build();

            await scheduler.ScheduleJob(job, trigger);
            await Task.Delay(TimeSpan.FromSeconds(10));
        }
    }
}
執行結果
最後,沒想到寫這該篇筆記時,已經推出 3.4.0 版本了,Orz 

沒有留言:

張貼留言