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

  • 相关阅读:
    web性能优化
    9.1_the end
    8.28_the end
    1.获取元素绝对位置
    8.14_end
    JavaScript 函数用途
    JavaScirpt事件处理
    《JavaScript语言精粹》读书笔记
    《图解http协议》之HTTPs学习笔记
    Laya 1.x 按文件夹TS代码合并
  • 原文地址:https://www.cnblogs.com/carlows/p/15560106.html
Copyright © 2011-2022 走看看