.Net Core 定时任务TimeJob(转载)

转载地址:https://www.cnblogs.com/ideacore/p/6297759.html

定时任务 Pomelo.AspNetCore.TimedJob

Pomelo.AspNetCore.TimedJob是一个.NET Core实现的定时任务job库,支持毫秒级定时任务、从数据库读取定时配置、同步异步定时任务等功能。

由.NET Core社区大神兼前微软MVP AmamiyaYuuko (入职微软之后就卸任MVP…)开发维护,不过好像没有开源,回头问下看看能不能开源掉。

作者自己的介绍文章: Timed Job – Pomelo扩展包系列

Startup.cs相关代码

我这边使用的话,首先肯定是先安装对应的包:Install-Package Pomelo.AspNetCore.TimedJob -Pre

然后在Startup.cs的ConfigureServices函数里面添加Service,在Configure函数里面Use一下。

// This method gets called by the runtime. Use this method to add services to the container.
publicvoidConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    //Add TimedJob services
    services.AddTimedJob();
}

 publicvoidConfigure(IApplicationBuilder app,
 IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //使用TimedJob
    app.UseTimedJob();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}

Job相关代码

接着新建一个类,明明为XXXJob.cs,引用命名空间using Pomelo.AspNetCore.TimedJob,XXXJob继承于Job,添加以下代码。

 public class AutoGetMovieListJob:Job
 {
     
     // Begin 起始时间;Interval执行时间间隔,单位是毫秒,建议使用以下格式,此处为3小时;
     //SkipWhileExecuting是否等待上一个执行完成,true为等待;
     [Invoke(Begin = "2016-11-29 22:10", Interval = 1000 * 3600*3, SkipWhileExecuting =true)]
     publicvoidRun()
     {
          //Job要执行的逻辑代码
          
         //LogHelper.Info("Start crawling");
         //AddToLatestMovieList(100);
         //AddToHotMovieList();
         //LogHelper.Info("Finish crawling");
     }
}

应该可以在一个Job类里写多个任务方法

猜你喜欢

转载自blog.csdn.net/csdn296/article/details/81161657