.net core 定时程序

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Star.Service.News
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Time Job Start");
            RunProgram().GetAwaiter().GetResult();
            Console.WriteLine("Hello World!");
            Console.Read();
        }

        private static async Task RunProgram()
        {
            try
            {
                // Grab the Scheduler instance from the Factory  
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                IScheduler scheduler = await factory.GetScheduler();

                // 启动任务调度器  
                await scheduler.Start();

                // 定义一个 Job              自定义定时任务类
                IJobDetail job = JobBuilder.Create<TimedBackgroundService>()
                    .WithIdentity("job1", "group1")
                    .Build();
                ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                    .WithIdentity("trigger1") // 给任务一个名字  
                    .StartAt(DateTime.Now) // 设置任务开始时间  
                    .ForJob("job1", "group1") //给任务指定一个分组  
                    .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(180)  //循环的时间 1秒1次 
                    .RepeatForever())
                    .Build();


                // 等待执行任务  
                await scheduler.ScheduleJob(job, trigger);

                // some sleep to show what's happening  
                //await Task.Delay(TimeSpan.FromMilliseconds(2000));  
            }
            catch (SchedulerException se)
            {
                await Console.Error.WriteLineAsync(se.ToString());
            }
        }
    }
}
using Quartz;
using Star.Helpers;
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Star.Service.News
{
    public class TimedBackgroundService : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            //return Console.Out.WriteLineAsync("Greetings from HelloJob!");
            JobKey key = context.JobDetail.Key;
            Process Proc = null;

            string exeName = "main";

            try
            {
                string destFilePath = "c://chromedriver.exe";
                string sourceFilePath = CommonHelper.GetPhysicalPath($"newspicker\\chromedriver.exe");

                if (!FileHelper.IsExistFile(destFilePath))
                {
                    FileHelper.CopyTo(sourceFilePath, destFilePath);
                }

                var myProcess = Process.GetProcesses();
                foreach (Process MyProcess in myProcess)
                {
                    //查找是否正在运行 
                    if (MyProcess.ProcessName.CompareTo(exeName) == 0
                        || MyProcess.ProcessName.CompareTo("chrome") == 0
                        || MyProcess.ProcessName.CompareTo("chromedriver") == 0)
                    {
                        MyProcess.Kill(); //杀死当前程序
                    }
                }
            }
            catch (Exception)
            {

            }

            try
            {
                string fileurl = CommonHelper.GetPhysicalPath($"{exeName}.exe");
                //启动外部程序
                Proc = Process.Start(fileurl);

                Proc.WaitForExit(120 * 1000);
                Proc.CloseMainWindow();//通过向进程的主窗口发送关闭消息来关闭拥有用户界面的进程

                context.MergedJobDataMap.Put("RunResult", ApiResult.Success($"新闻采集程序运行时间{(Proc.StartTime - Proc.ExitTime).Milliseconds}"));
            }
            catch (Exception ex)
            {
                Proc?.WaitForExit(60 * 1000);
                Proc?.CloseMainWindow();
                Proc?.Close();

                context.MergedJobDataMap.Put("RunResult", ApiResult.Fail(ApiEnum.Error, $"{key.Group}.{key.Name}:{ ex.Message}"));
            }
            finally
            {
                Proc.Close();//释放与此组件关联的所有资源
            }
            return Task.CompletedTask;
        }
    }
}

 

.net core 定时程序

全文结束