如何编写后台定时任务调度? #

通过官方脚手架,示例工程已经有例子,参考如下:

using DotXxlJob.Core;
using DotXxlJob.Core.Model;
using Mall3s.Oms.Interfaces.ExchangeRate;
using Mall3s.Dependency;
using System;
using System.Threading.Tasks;

namespace Mall3s.Oms.Api.JobHandler
{
    /// <summary>
    /// 同步汇率Job
    /// </summary>
    [JobHandler("SyncExchangeRateHandler")]
    public class SyncExchangeRateHandler : IJobHandler, IScoped
    {
        private readonly IExchangeRateService _exchangeRateService;

        /// <summary>
        /// 构造
        /// </summary>
        public SyncExchangeRateHandler()
        {
            _exchangeRateService = App.GetService<IExchangeRateService>();
        }
        public void Dispose()
        {
            //服务停止前的操作,如通知等操作可在这里写
            Console.WriteLine("任务停止");
        }

        /// <summary>
        /// 执行逻辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        /// <exception cref="global::System.NotImplementedException"></exception>
        public async Task<ReturnT> Execute(JobExecuteContext context)
        {
            /*var data = await _exchangeRateService.GetExchangeRate(DateTime.Parse("2022-02-23"), "USD", "CNY");
            Console.WriteLine($"{data.Date}:USD->CNY 汇率为{data.Rate}");*/
            
            return ReturnT.Success("成功");
        }
    }
}

image-20230308225803876

startup中启动xxl-job

//可选,XXLJOB任务
builder.Services.AddXxlJobAuto(builder.Configuration);

//可选,XXLJOB任务
app.UseXxlJobExecutor();

登录xxl-job查看任务。

image-20230308225955467

image-20230308230005575

#

上次更新: 3/8/2023, 4:23:32 PM