在WinForms中的使用FluentScheduler实现定时任务

 

在WinForm程序中使用 FluentScheduler框架实现一个多任务的定时执行功能。

 

1、使用Nuget 安装 FluentScheduler 包,默认使用最新稳定版

2、以下是 实现功能的代码:

 1 using System;
 2 using System.Windows.Forms;
 3 using FluentScheduler;
 4 
 5 public partial class MainForm : Form
 6 {
 7     public MainForm()
 8     {
 9         InitializeComponent();
10         JobManager.Initialize(new MyRegistry(Query));
11     }
12 
13     public void Query()
14     {
15         // 这里实现Query方法的内容
16     }
17 
18     protected override void OnFormClosing(FormClosingEventArgs e)
19     {
20         // 确保在窗体关闭时停止并清理FluentScheduler的任务
21         JobManager.StopAndBlock(); 
22         base.OnFormClosing(e);
23     }
24 
25     private class MyRegistry : Registry
26     {
27         public MyRegistry(Action queryAction)
28         {
29             // 创建每周一至周五6点5分执行的任务
30             Schedule(() =>
31             {
32                 if (Application.OpenForms.Count > 0)
33                 {
34                     Form mainForm = Application.OpenForms[0]; // 获取主窗体
35                     if (mainForm.InvokeRequired)
36                     {
37                         mainForm.Invoke(queryAction); // 通过委托在UI线程上执行Query()
38                     }
39                     else
40                     {
41                         queryAction(); // 直接执行Query()
42                     }
43                 }
44             }).ToRunEvery(1).Weeks().OnWeekdays().At(6, 5);
45         }
46     }
47 }
48 
49 // 程序入口
50 static class Program
51 {
52     [STAThread]
53     static void Main()
54     {
55         Application.EnableVisualStyles();
56         Application.SetCompatibleTextRenderingDefault(false);
57         Application.Run(new MainForm());
58     }
59 }

 

使用框架的特点:

1、将定时任务的逻辑与UI逻辑分离。不直接从调度器线程更新UI,而是通过更新UI的方法来处理。

2、只在需要时创建新的委托(Action),避免重复创建委托,这在频繁触发的任务中尤其重要。

3、确保应用程序关闭时正确地清理资源。

posted @ 2024-03-15 10:13  DotNet码农  阅读(87)  评论(0编辑  收藏  举报
/*粒子线条,鼠标移动会以鼠标为中心吸附的特效*/