在日常任务/cron 作业上运行程序



当您安排任务或 chron 作业时,究竟涉及什么?我有一个应用程序,我的经理想每天在特定时间运行,该应用程序依赖于用户输入,但它旨在保存用户首选项并加载这些首选项,只要用户单击按钮,它就会执行任务。假设输入的所有数据都有效,我该如何每天强制执行此操作。这是在MVC/ASP.NET 中,所以它会在Windows上。但是,如果有人可以解释它如何与 Linux 中的 cron 作业一起工作,我也可以从那里弄清楚。我是否需要编写调用 mvc 代码的脚本?或者有什么建议吗?

这是一个示例 Windows 服务,每天在给定的一组时间运行,我认为这会对您有所帮助。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace DemoWinService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
        System.Timers.Timer _timer;
        List<TimeSpan> timeToRun = new List<TimeSpan>();
        public void OnStart(string[] args)
        {
            string timeToRunStr = "19:01;19:02;19:00"; //Time interval on which task will run
            var timeStrArray = timeToRunStr.Split(';');
            CultureInfo provider = CultureInfo.InvariantCulture;
            foreach (var strTime in timeStrArray)
            {
                timeToRun.Add(TimeSpan.ParseExact(strTime, "g", provider));
            }
            _timer = new System.Timers.Timer(60 * 100 * 1000);
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            ResetTimer();
        }

        void ResetTimer()
        {
            TimeSpan currentTime = DateTime.Now.TimeOfDay;
            TimeSpan? nextRunTime = null;
            foreach (TimeSpan runTime in timeToRun)
            {
                if (currentTime < runTime)
                {
                    nextRunTime = runTime;
                    break;
                }
            }
            if (!nextRunTime.HasValue)
            {
                nextRunTime = timeToRun[0].Add(new TimeSpan(24, 0, 0));
            }
            _timer.Interval = (nextRunTime.Value - currentTime).TotalMilliseconds;
            _timer.Enabled = true;
        }
        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            _timer.Enabled = false;
            Console.WriteLine("Hello at " + DateTime.Now.ToString()); //You can perform your task here
            ResetTimer();
        }
    }
}

最新更新