source: FarmatikoServices/Services/UpdateDataHostedService.cs@ 472dd7e

Last change on this file since 472dd7e was f554983, checked in by Dimitar Slezenkovski <dslezenkovski@…>, 4 years ago

Add cron job for updating data, with Quartz.NET

  • Property mode set to 100644
File size: 2.2 KB
Line 
1using FarmatikoServices.Services.JobDTO;
2using Microsoft.Extensions.Hosting;
3using Quartz;
4using Quartz.Spi;
5using System;
6using System.Collections.Generic;
7using System.Text;
8using System.Threading;
9using System.Threading.Tasks;
10
11namespace 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}
Note: See TracBrowser for help on using the repository browser.