C# 每分整秒運行
using System.Dynamic;
namespace CycleSeco
{
internal class Program
{
static void Main(string[] args)
{
setTaskAtFixedTime();
while (true)
{
Console.WriteLine($"{DateTime.Now}");
System.Threading.Thread.Sleep(1000);
}
}
static DateTime LastTime;
private static void setTaskAtFixedTime()
{
DateTime now = DateTime.Now;
var WaitMinSeco = now.Subtract(LastTime).TotalMilliseconds;
if (WaitMinSeco < 1000)
{
Console.WriteLine($"Wait {1000 - Convert.ToInt32(WaitMinSeco)} MinSeco");
System.Threading.Thread.Sleep(1000 - Convert.ToInt32(WaitMinSeco));
}
int[] SetSeco = new int[] { 0, 10, 20, 30, 40, 50 };
DateTime NextTime = DateTime.Now;
var bb = SetSeco.Select(x => now.AddSeconds(-now.Second).AddSeconds(x)).Where(x => x >= now).FirstOrDefault();
var cc = SetSeco.Select(x => now.AddSeconds(-now.Second).AddMinutes(1).AddSeconds(x)).Where(x => x >= now).FirstOrDefault();
if (bb.Year > 1)
{
NextTime = bb;
Console.WriteLine($"Next Time{bb}");
}
else if (cc.Year > 1)
{
NextTime = cc;
Console.WriteLine($"Next Time{cc}");
}
int msUntilFour = (int)((NextTime - now).TotalMilliseconds);
var t = new System.Threading.Timer(doAt1AM);
t.Change(msUntilFour, Timeout.Infinite);
LastTime = DateTime.Now;
}
//要執行的任務
private static void doAt1AM(object state)
{
// 當前觸發時間
DateTime Trigger = DateTime.Now;
//執行功能...
Console.WriteLine($"Run {Trigger}");
System.Threading.Thread.Sleep(1000);
//再次設定
setTaskAtFixedTime();
}
}
}
留言
張貼留言