iT邦幫忙

0

NET6 Quartz 排程未正確執行問題

  • 分享至 

  • xImage

JobStart("TurnOn", "Cron", "TEST", "on", "0/5 0 12 ? * 1,3,5 "); 這是資料庫抓出來後會回傳這些

使用WPF NET6 目前打開程式後沒有錯誤訊息
但是排程沒有執行messagebox.show出來

Task.cs

using System;
using System.Threading.Tasks;
using System.Windows;
using Quartz;

namespace KoModel.Quartz
{
    #region Job
    //2、創建一個任務 Create<Class(Task Name)> <= QuartzConfig.cs 
    public class MyJob
    {
        public IJobDetail TurnOn(string title, string groups = "on")
        {
            IJobDetail job = JobBuilder.Create<TurnOn>().WithIdentity(title, groups).Build();
            return job;
        }
    }
    #endregion

    #region Task
    //打上DisallowConcurrentExecution標簽讓Job進行單線程跑,避免沒跑完時的重覆執行。
    [DisallowConcurrentExecution]
    public class TurnOn : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            return Task.Run(() =>
            {
                MessageBox.Show("開啟 現在時間:" + DateTime.Now);
            });
        }
    }
    #endregion
}

Quartz.cs

using Quartz.Impl;
using Quartz;
using System;

namespace KoModel.Quartz
{
    public static class QuartzConfig
    {
        //調度器工廠
        private static ISchedulerFactory? schedulerFactory;
        //調度器
        private static IScheduler? scheduler;

        public static ITrigger trigger(string type, string title, string groups = "on", string time = "5")
        {
            //3、創建一個觸發器(有4種觸發器供選擇)
            //重複執行:WithRepeatCount(count) / RepeatForever(count)
            //間格時間:WithInterval(time)
            //定時執行:StartAt() / StartNow()
            //設定優先:WithPriority(),default 5

            ITrigger trigger;
            switch (type)
            {
                case "Simple":
                    #region 觸發器1:WithSimpleSchedule 
                    trigger = TriggerBuilder.Create()
                        .WithIdentity(title, groups)
                        .WithSimpleSchedule(x => x.WithIntervalInSeconds(int.Parse(time)).RepeatForever())
                        .Build();
                    #endregion
                    break;
                case "Daily":
                    #region 觸發器2:WithDailyTimeIntervalSchedule
                    trigger = TriggerBuilder.Create()
                        .WithIdentity(title, groups)
                        .WithDailyTimeIntervalSchedule(x => x.OnEveryDay().WithIntervalInSeconds(int.Parse(time)))
                        .Build();
                    #endregion
                    break;
                case "Calendar":
                    #region 觸發器3:WithCalendarIntervalSchedule
                    trigger = TriggerBuilder.Create()
                        .WithIdentity(title, groups)
                        .WithCalendarIntervalSchedule(x => x.WithIntervalInSeconds(int.Parse(time)))
                        .Build();
                    #endregion
                    break;
                case "Cron":
                default:
                    #region 觸發器4:WithCronSchedule()
                    trigger = TriggerBuilder.Create()
                        .WithIdentity(title, groups)
                        .WithCronSchedule(time)
                        .Build();
                    #endregion
                    break;
            }
            return trigger;
        }

        public static async void Run(IJobDetail job, ITrigger trigger)
        {
            //1、創建一個調度器
            schedulerFactory = new StdSchedulerFactory();
            scheduler = await schedulerFactory.GetScheduler();
            await scheduler.Start();

            JobKey jobKey = new JobKey(job.Key.Name, job.Key.Group);
            TriggerKey triggerKey = new TriggerKey(trigger.Key.Name, trigger.Key.Group);

            bool exists = await scheduler.CheckExists(jobKey);
            if (!exists)
            {
                // 該工作還沒有執行
                //4、將任務與觸發器添加到調度器中
                await scheduler.ScheduleJob(job, trigger);
            }
            //5、開始執行
            await scheduler.Start();
        }

        public static void Shutdown()
        {
            if (scheduler != null)
            {
                scheduler.Shutdown(true);
            }
        }
    }
}

ShellViewModel.cs

public async void JobStart(string functionName, string type, string title, string groups = "on", string time = "5")
        {
            ITrigger iTrigger = QuartzConfig.trigger(type, title, groups, time);
            //// 取得 ExampleClass 的 Type 物件
            MyJob myJob = new MyJob();
            //// 從 Type 物件中查找指定名稱的方法
            MethodInfo methodInfo = typeof(MyJob).GetMethod(functionName);

            IJobDetail iJobDetail;
            //// 如果找到了該方法,調用它
            if (methodInfo != null)
            {
                object[] parameters = new object[] { title, groups };
                iJobDetail = (IJobDetail)methodInfo.Invoke(myJob, parameters);
                QuartzConfig.Run(iJobDetail, iTrigger);
            }
            else
            {
                MessageBox.Show("未定義此排程");
            }
        }

public List<JobViewList> SelectJobList()
        {
            List<JobViewList> entries = new List<JobViewList>();

            using (var db = new SqliteConnection(DataAccess.GetConnStringForSelf()))
            {
                db.Open();
                var command = new SqliteCommand("SELECT id, title, sCron, eCron, groups From JobList", db);
                SqliteDataReader query = command.ExecuteReader();

                while (query.Read())
                {
                    JobViewList joblist = new JobViewList();
                    joblist.id = int.Parse(query["ID"].ToString());
                    joblist.title = query["Title"].ToString();
                    joblist.sCron = CronReString("Time", query["sCron"].ToString());
                    joblist.eCron = CronReString("Time", query["eCron"].ToString());
                    joblist.StringDay = CronReString("WeekDay", query["sCron"].ToString());
                    joblist.groups = query["groups"].ToString();
                    entries.Add(joblist);

                    JobStart("TurnOn", "Cron", query["Title"].ToString(), "on", query["sCron"].ToString());
                    //JobStart("TurnOff", "Cron", query["Title"].ToString(), "off", query["eCron"].ToString());
                }

                db.Close();
            }

            return entries;
        }
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
JamesDoge
iT邦高手 1 級 ‧ 2023-03-21 08:12:36
public Task Execute(IJobExecutionContext context)
{
    return Task.Run(() =>
    {
        Application.Current.Dispatcher.Invoke(() =>
        {
            MessageBox.Show("開啟 現在時間:" + DateTime.Now);
        });
    });
}

柯柯 iT邦新手 2 級 ‧ 2023-03-23 10:17:51 檢舉

後來正常了 好像是Cron的格式問題 調一調就正常了 也不確定 是不是異步問題

我要發表回答

立即登入回答