自訂 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));
}
}
}
執行結果- 參考資料
- StackOverFlow 討論
沒有留言:
張貼留言