需要重启,那就要一个时间来效验,写法都有很多。我这里采用ini来存放。
Time 记录要重启的时间,验证时间。
Day 用来累加天数。
代码如下:
[Reboot]
Time=02:02:01
Day=3
使用System.Timers.Timer循环验证时间(不知道始终对占用资源是否会太大)
代码如下:
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") == retime)
{
Shoutdown.DoExitWin(0x00000002);
}
}
服务首次启动初始化重启的时间以及天数,初始化时候读取ini文件,把时间放进变量里,将天数累加3天。(减少读写I/O的开销)
始终不停的循环验证。
代码如下:
protected override void OnStart(string[] args)
{
ini = new IniFile(AppDomain.CurrentDomain.BaseDirectory + "Current.ini");
time = ini.IniReadValue("Reboot", "Time");
day = ini.IniReadValue("Reboot", "Day");
retime = DateTime.Now.AddDays(double.Parse(day)).ToString("yyyy-MM-dd ") + time;
autoTimer.AutoReset = true;
autoTimer.Enabled = true;
autoTimer.Elapsed += Timer_Elapsed;
autoTimer.Start();
}
这里可以改造成用线程来做,我想应该比这个会好。
放出一段自动备份SQLSERVER的代码端,将后会发布。
代码如下:
private readonly Dictionarystring, bool cache =
new Dictionarystring, bool();
private readonly IniFile ini = new IniFile(SysUtil.GetMapPath("Task.ini"));
private bool _flag;
private string day;
private string fHour;
private string fWeek;
private string hour;
private Thread timeThread;
protected override void OnStart(string[] args)
{
Go();
}
protected override void OnStop()
{
StopThread();
}
/// summary
/// 执行
/// /summary
public void Go()
{
day = DateTime.Now.ToString("yyyy-MM-dd");
fWeek = ini.IniReadValue("Task", "Week");
fHour = ini.IniReadValue("Task", "Hour");
RunThread();
}
/// summary
/// 执行线程
/// /summary
private void RunThread()
{
//这里开始线程
_flag = true;
timeThread = new Thread(ThreadTimer);
timeThread.Start();
}
/// summary
/// 停止线程
/// /summary
private void StopThread()
{
_flag = false;
if (timeThread != null) timeThread.Abort();
}
/// summary
/// 线程方法
/// /summary
public void ThreadTimer()
{
while (_flag)
{
if (fWeek == "") //按天
{
RunBackup();
}
else
{
// 按周
if (WeekSwitch(fWeek) == DateUtil.getWeek(DateTime.Now) && WeekSwitch(fWeek) != "")
{
RunBackup();
}
}
}
}
/// summary
/// 数据库列表
/// /summary
private DataTable GetTaskList()
{
DataSet ds = new DataSet();
ds.ReadXml(SysUtil.GetMapPath("Db.xml"));
return ds.Tables["DataSet"];
}
private void RunBackup()
{
if (!File.Exists(SysUtil.GetMapPath("Db.xml"))) return;
day = DateTime.Now.ToString("yyyy-MM-dd");
hour = DateTime.Now.ToString("HH");
if (hour.Equals(fHour))
{
if (!cache.ContainsKey(day)) cache.Add(day, false);
if (fWeek != "" && cache[day] == false)
{
if (WeekSwitch(fWeek) == DateUtil.getWeek(DateTime.Parse(day)))
{
StartWork();
cache[day] = true;
}
}
else
{
if (cache[day] == false)
{
StartWork();
cache[day] = true;
}
}
}
当前1/2页 12下一页 猜你喜欢