-
Notifications
You must be signed in to change notification settings - Fork 747
/
HangfireJobRunner.cs
85 lines (73 loc) · 3.01 KB
/
HangfireJobRunner.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// -----------------------------------------------------------------------
// <copyright file="HangfireJobRunner.cs" company="OSharp开源团队">
// Copyright (c) 2014-2018 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2018-12-31 17:36</last-date>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Hangfire;
using Liuliu.Demo.Identity;
using Liuliu.Demo.Identity.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using OSharp.Collections;
using OSharp.Dependency;
using OSharp.Entity;
using OSharp.Hangfire;
namespace Liuliu.Demo.Web.Hangfire
{
[Dependency(ServiceLifetime.Singleton)]
public class HangfireJobRunner : IHangfireJobRunner
{
public void Start()
{
BackgroundJob.Enqueue<UserManager<User>>(m => m.FindByIdAsync("1"));
string jobId = BackgroundJob.Schedule<UserManager<User>>(m => m.FindByIdAsync("2"), TimeSpan.FromMinutes(2));
BackgroundJob.ContinueJobWith<TestHangfireJob>(jobId, m => m.GetUserCount());
RecurringJob.AddOrUpdate<TestHangfireJob>("TestHangfireJob.GetUserCount", m => m.GetUserCount(), Cron.Minutely);
RecurringJob.AddOrUpdate<TestHangfireJob>("TestHangfireJob.LockUser2", m => m.LockUser2(), Cron.Minutely);
}
}
public class TestHangfireJob
{
private readonly IIdentityContract _identityContract;
private readonly IServiceProvider _provider;
/// <summary>
/// 初始化一个<see cref="TestHangfireJob"/>类型的新实例
/// </summary>
public TestHangfireJob(IIdentityContract identityContract, IServiceProvider provider)
{
_identityContract = identityContract;
_provider = provider;
}
/// <summary>
/// 获取用户数量
/// </summary>
public string GetUserCount()
{
List<string> list = new List<string>();
list.Add(_identityContract.Users.Count().ToString());
list.Add(_identityContract.GetHashCode().ToString());
return list.ExpandAndToString();
}
public async Task<string> LockUser2()
{
List<string> list = new List<string>();
UserManager<User> userManager = _provider.GetRequiredService<UserManager<User>>();
User user2 = await userManager.FindByIdAsync("2");
list.Add($"user2.IsLocked: {user2.IsLocked}");
user2.IsLocked = !user2.IsLocked;
IUnitOfWork unitOfWork = _provider.GetUnitOfWork(true);
await userManager.UpdateAsync(user2);
await unitOfWork.CommitAsync();
user2 = await userManager.FindByIdAsync("2");
list.Add($"user2.IsLocked: {user2.IsLocked}");
return list.ExpandAndToString();
}
}
}