zoukankan      html  css  js  c++  java
  • NetCore,Web,定时任务

    web网站要定时执行一下指令,通常是专门给它写一个服务,但是建一个小网站,还专门给它写服务,感觉小题大作了,直接写web代码里不好吗?

    首先我们写一个配置读取方法,因为我们需要读取网站绑定的域名,当然你要是把网站域名写死在代码里,就不用这个了.

        public static class AppSetting
        {
            public static IConfigurationRoot configuration;
            static AppSetting()
            {
                configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true)
                    .Build();
            }
            public static string GetConfig(string key)
            {
                try
                {
                    return configuration.GetSection("AppConfig")[key].ToString();
                }
                catch (Exception)
                {
                    return "";
                }
            }
        }

    然后我们在appsetting.json里写上我们的配置

      "AppConfig": {
        "ServerUrl": "http://www.mysite.com:5000"
      },

    接下来在Startup.cs启动器里,Configure方法的最后写上异步代码

    Task.Run(() =>
    {
        var time = DateTime.Today.AddDays(-1);
        while (true)
        {
            string url = AppSetting.GetConfig("ServerUrl") + "/Index/Space";//本站的一个空白控制器页面,返回 return Content("");
            WebHelper.RequestGetUrl(url);//自己封装的一个get请求方法,请求上面的空白页面,用处是保持心跳,防止进程休眠而导致本方法失效.
            var now = DateTime.Today;
            //半夜指定时间执行计划任务
            if (DateTime.Now.TimeOfDay > new TimeSpan(0, 0, 0) && DateTime.Now.TimeOfDay < new TimeSpan(0, 30, 0))
            {
                if (now > time)
                {
                    using (var scoped = Startup.ApplicationServices.CreateScope())
                    {
                        var db = scoped.ServiceProvider.GetService<DBContext>();
                        try
                        {
                            //我的计划任务
                        }
                        catch (Exception e)
                        {
                            //记录错误信息
                        }
                    }
                    time = DateTime.Today;
                }
            }
            Thread.Sleep(300000);//5分钟执行一次
        }
    });        

    使用的EntityFrameworkCore

  • 相关阅读:
    Hadoop Partitioner编程
    Hadoop Mapreduce之WordCount实现
    在linux下编写maven程序
    Hadoop RPC通信机制
    Hadoop 源码分析——Job提交过程
    HDFS的java接口
    hadoop 文件系统shell命令
    同步 vs 异步
    C++ STL详解
    C++中struct和class定义类区别
  • 原文地址:https://www.cnblogs.com/carlows/p/15560106.html
Copyright © 2011-2022 走看看