forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJob1TimedService.cs
More file actions
60 lines (49 loc) · 1.6 KB
/
Job1TimedService.cs
File metadata and controls
60 lines (49 loc) · 1.6 KB
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
59
60
using Blog.Core.Common;
using Blog.Core.IServices;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Blog.Core.Tasks
{
public class Job1TimedService : IHostedService, IDisposable
{
private Timer _timer;
private readonly IBlogArticleServices _blogArticleServices;
// 这里可以注入
public Job1TimedService(IBlogArticleServices blogArticleServices)
{
_blogArticleServices = blogArticleServices;
}
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Job 1 is starting.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(60 * 60));//一个小时
return Task.CompletedTask;
}
private void DoWork(object state)
{
try
{
var model = _blogArticleServices.GetBlogDetails(1).Result;
Console.WriteLine($"Job 1 启动成功,获取id=1的博客title为:{model?.btitle}");
}
catch (Exception ex)
{
Console.WriteLine($"Error:{ex.Message}");
}
ConsoleHelper.WriteSuccessLine($"Job 1: {DateTime.Now}");
}
public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Job 1 is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
}