-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathScheduledService.cs
58 lines (48 loc) · 2.19 KB
/
ScheduledService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using Microsoft.Extensions.Hosting;
using Quartz;
// https://www.quartz-scheduler.net/documentation/quartz-4.x/quick-start.html
// https://andrewlock.net/using-quartz-net-with-asp-net-core-and-worker-services/
// https://github.com/skiptirengu/Hosting.Extensions.Quartz/blob/master/src/HostBuilderExtensions.cs#L71
public class ScheduledService : BackgroundService
{
private readonly Lazy<Task<IScheduler>> _scheduler;
public ScheduledService(ISchedulerFactory factory) =>
_scheduler = new Lazy<Task<IScheduler>>(() => factory.GetScheduler());
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
// Grab the Scheduler instance from the Factory
var scheduler = await _scheduler.Value;
// define the job and tie it to our HelloJob class
var job = JobBuilder.Create<HelloJob>()
.WithIdentity("job1", "group1")
.Build();
// Trigger the job to run now, and then repeat every 10 seconds
var trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(s => s
.WithIntervalInSeconds(1)
.RepeatForever()
)
.Build();
// Tell Quartz to schedule the job using our trigger
await scheduler.ScheduleJob(job, trigger);
// and start it off
await scheduler.Start(cancellationToken);
Console.WriteLine("A scheduler has been started.");
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
var scheduler = await _scheduler.Value;
await scheduler.Shutdown(cancellationToken);
Console.WriteLine("A scheduler has been stopped.");
}
[DisallowConcurrentExecution]
// Use DisallowConcurrentExecution attribute to prevent Quartz.NET from trying to run the same job concurrently.
// https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/more-about-jobs.html#job-state-and-concurrency
public class HelloJob : IJob
{
public async Task Execute(IJobExecutionContext context) =>
await Console.Out.WriteLineAsync("Greetings from HelloJob!");
}
}