zoukankan      html  css  js  c++  java
  • 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     时间差不多

     

  • 相关阅读:
    问题:Failed to execute goal org.apache.maven.plugins:mavencompilerplugin:3.5.1:compile (defaultcompile)
    STL容器的内存分配
    C++中的引用到底是什么
    解决eclipse无法解析shared_ptr
    Deleted pointer causes undefined behaviour
    诞生于饭桌上的jcSQL语言
    状压dp做题笔记
    TC做题笔记
    数据结构做题笔记
    POI做题笔记
  • 原文地址:https://www.cnblogs.com/ZkbFighting/p/11294467.html
Copyright © 2011-2022 走看看