廢話少說,直接上代碼:
/// <summary> /// 開啟定時聯動定時任務 /// </summary> public void StartTimingTouchLinkAsync() { string recurringJobId = "設備聯動定時執行"; string cronStr = "*/5 * * * * *"; RecurringJob.AddOrUpdate(recurringJobId,this.TimingTouchLinkAsync(), cronStr, TimeZoneInfo.Local); } /// <summary> /// 定時觸發(每5秒) 聯動觸發(從關系庫獲取數據) /// </summary> /// <returns></returns> [UnitOfWork] public virtual async Task TimingTouchLinkAsync() { /***省略部分代碼 ***/ var isMeet = await IsMeetCondition(conditionSymbol, conditionValue, intimeValue); /***省略部分代碼 ***/ //觸發執行聯動 await this.DoLinkAsync(currentLinkId); /***省略部分代碼 ***/ }
定時任務執行結果:

System.InvalidOperationException: Recurring job can't be scheduled, see inner exception for details. ---> Hangfire.Common.JobLoadException: Could not load the job. See inner exception for the details. ---> System.InvalidOperationException: The type `Awing.IBMS.Application.Business.LinkAppService` does not contain a method with signature `TimingTouchLinkAsync()` at Hangfire.Storage.InvocationData.DeserializeJob() --- End of inner exception stack trace --- at Hangfire.Storage.InvocationData.DeserializeJob() at Hangfire.RecurringJobEntity..ctor(String recurringJobId, IDictionary`2 recurringJob, ITimeZoneResolver timeZoneResolver, DateTime now) --- End of inner exception stack trace --- at Hangfire.Server.RecurringJobScheduler.ScheduleRecurringJob(BackgroundProcessContext context, IStorageConnection connection, String recurringJobId, RecurringJobEntity recurringJob, DateTime now)
原因分析:
明明有TimingTouchLinkAsync()方法,錯誤提示卻還是不存在該方法,應該是方法中出現了錯誤。
因為TimingTouchLinkAsync()方法中同步方法、異步方法並存,故該方法可能出現同步異步執行時間混亂問題。
解決辦法是為該方法。
1.方法添加屬性 UnitOfWork
2.方法采用虛方法 virtual
3.注意方法中調用的其他方法也要采用上述2條。
