剛剛去了一家公司面試,他們讓我上機做一個類似計劃任務的模組,在設定檔裡寫要執行的時間,讓程式定時執行。
1.建立設定檔App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!--設定每月執行計畫任務的日期,先設定每月的16號,17號,25號執行-->
<add key ="DateNum" value ="16,17,25"/>
</appSettings>
</configuration>
2. 建立PlanWork.cs檔案
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Timers;
namespace PlanWork
{
public class PlanWork
{
static void Main(string[] args)
{
Myplan mp = new Myplan();
//*************************************************
//設定間隔時間是15天,測試的時候設定時間為1000納秒
//Timer t = new Timer(15 * 24 * 60 * 60000);
Timer t = new Timer(1000);
//*************************************************
//綁定定時觸發的函數
t.Elapsed += new ElapsedEventHandler(mp.RunMyplan);
t.Start();
Console.ReadLine();
}
}
public class Myplan
{
public void RunMyplan(Object source, ElapsedEventArgs e)
{
//讀取設定檔設定的日期時間
string SetDate = ConfigurationManager.AppSettings["DateNum"].ToString();
//擷取現在的系統時間
DateTime nowTime = System.DateTime.Now;
string d = nowTime.Day.ToString(); //取日期
//比較是否符合設定的時間,SetDate中是否有d的存在
int i = SetDate.IndexOf(d);
if (i >= 0)
{
//計劃任務要執行程式
Console.Write("\nToday is " + d + " day!");
}
}
}
}
這樣一個計劃任務的小程式就ok了。