1 | using FarmatikoServices.Services.JobDTO;
|
---|
2 | using Microsoft.Extensions.Hosting;
|
---|
3 | using Quartz;
|
---|
4 | using Quartz.Spi;
|
---|
5 | using System;
|
---|
6 | using System.Collections.Generic;
|
---|
7 | using System.Text;
|
---|
8 | using System.Threading;
|
---|
9 | using System.Threading.Tasks;
|
---|
10 |
|
---|
11 | namespace FarmatikoServices.Services
|
---|
12 | {
|
---|
13 | public class UpdateDataHostedService : IHostedService
|
---|
14 | {
|
---|
15 | private readonly ISchedulerFactory _schedulerFactory;
|
---|
16 | private readonly IJobFactory _jobFactory;
|
---|
17 | private readonly IEnumerable<JobSchedule> _jobSchedules;
|
---|
18 |
|
---|
19 | public UpdateDataHostedService(
|
---|
20 | ISchedulerFactory schedulerFactory,
|
---|
21 | IJobFactory jobFactory,
|
---|
22 | IEnumerable<JobSchedule> jobSchedules)
|
---|
23 | {
|
---|
24 | _schedulerFactory = schedulerFactory;
|
---|
25 | _jobSchedules = jobSchedules;
|
---|
26 | _jobFactory = jobFactory;
|
---|
27 | }
|
---|
28 | public IScheduler Scheduler { get; set; }
|
---|
29 |
|
---|
30 | public async Task StartAsync(CancellationToken cancellationToken)
|
---|
31 | {
|
---|
32 | Scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
|
---|
33 | Scheduler.JobFactory = _jobFactory;
|
---|
34 |
|
---|
35 | foreach (var jobSchedule in _jobSchedules)
|
---|
36 | {
|
---|
37 | var job = CreateJob(jobSchedule);
|
---|
38 | var trigger = CreateTrigger(jobSchedule);
|
---|
39 |
|
---|
40 | await Scheduler.ScheduleJob(job, trigger, cancellationToken);
|
---|
41 | }
|
---|
42 |
|
---|
43 | await Scheduler.Start(cancellationToken);
|
---|
44 | }
|
---|
45 |
|
---|
46 | public async Task StopAsync(CancellationToken cancellationToken)
|
---|
47 | {
|
---|
48 | await Scheduler?.Shutdown(cancellationToken);
|
---|
49 | }
|
---|
50 |
|
---|
51 | private static IJobDetail CreateJob(JobSchedule schedule)
|
---|
52 | {
|
---|
53 | var jobType = schedule.JobType;
|
---|
54 | return JobBuilder
|
---|
55 | .Create(jobType)
|
---|
56 | .WithIdentity(jobType.FullName)
|
---|
57 | .WithDescription(jobType.Name)
|
---|
58 | .Build();
|
---|
59 | }
|
---|
60 |
|
---|
61 | private static ITrigger CreateTrigger(JobSchedule schedule)
|
---|
62 | {
|
---|
63 | return TriggerBuilder
|
---|
64 | .Create()
|
---|
65 | .WithIdentity($"{schedule.JobType.FullName}.trigger")
|
---|
66 | .WithCronSchedule(schedule.CronExpression)
|
---|
67 | .WithDescription(schedule.CronExpression)
|
---|
68 | .Build();
|
---|
69 | }
|
---|
70 | }
|
---|
71 | }
|
---|