Core 定时任务之HangFire

ASP.NET Core 使用 Hangfire 很简单,首先,Nuget 安装程序包

> install-package Hangfire -pre

然后ConfigureServices添加配置代码:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
             //配置好数据库链接后,会在数据库对应的表中生成一些对应的表
            services.AddHangfire(x => x.UseSqlServerStorage("Data Source=LocalHost;Initial Catalog= Tab_Hangfire;Integrated Security=true;Persist Security Info=true"));

            //services.AddTimedJob();
        }

然后Configure添加配置代码:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHangfireServer();
            app.UseHangfireDashboard();
            //"0 3 * * *"
            //RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring!"), Cron.Minutely());
//这里有几个参数:<要执行的方法所在的类> http://localhost:52815/hangfire/周期性作业的编号名字 类的方法和参数 Corn表达式 RecurringJob.AddOrUpdate<InsertData>("Prozkb",p=>p.insert("zkb"), "0 */1 * * * ?", System.TimeZoneInfo.Local);
//这个Prozkb是RecurringJobId
//app.UseTimedJob(); app.UseMvc(); }
 public class InsertData
    {
        public void insert(string name)
        {
            string sql = "  insert into InsertData values('"+ name + "','',GETDATE())";           
            ExeNonQuery_B2B(sql);
        }

        public static void ExeNonQuery_B2B(string cmd)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=LocalHost;Initial Catalog= Tab_Hangfire;Integrated Security=true;Persist Security Info=true";
            con.Open();
            SqlCommand com = new SqlCommand();
            com.Connection = con;
            com.CommandType = CommandType.Text;
            com.CommandText = cmd;
            SqlDataReader dr = com.ExecuteReader();
            dr.Close();
            con.Close();
        }
    }

http://localhost:52815/hangfire/           执行到数据库差不多就是一分钟左右

12:38:06.4170000     时间差不多

 

 

 

posted @ 2019-08-03 12:43  ProZkb  阅读(788)  评论(0编辑  收藏  举报