定时任务
1. 代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
private delegate void InvokeCallback(); // 声明代理
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(t_taks_run);
timer.Interval = 5 * 1000; // 5 秒请求一次
timer.Start();
}
public void t_taks_run(object sender, System.Timers.ElapsedEventArgs e)
{
PrintInfo();
//Console.WriteLine($"执行了:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
}
public void PrintInfo()
{
if (richTextBox1.InvokeRequired)
{
InvokeCallback msgCallback = new InvokeCallback(PrintInfo);
richTextBox1.Invoke(msgCallback);
}
else
{
richTextBox1.Text += $"执行了:{DateTime.Now:yyyy-MM-dd HH:mm:ss}\n";
}
}
}
}
QQ截图20230131104436.png
网友评论