欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net core 定时程序

程序员文章站 2023-10-19 11:33:08
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Quartz; using Quartz.Imp... ......
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;
        }
    }
}