0
我有Windows服務問題。我正在寫一個定時器的服務,這將會花費一些時間並且不斷重複。C#Windows服務僅在方法完成後重新運行
在我的代碼中,我希望timer1_Tick方法只在完成後重新運行,而不是在每2秒後重新運行。我怎樣才能實現它?任何指針?
這是我的代碼的外觀:
using System;
using System.ServiceProcess;
using System.Timers;
namespace TestWindowsService
{
public partial class Scheduler : ServiceBase
{
private Timer timer1 = null;
public Scheduler()
{
InitializeComponent();
}
public void onDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
timer1 = new Timer();
this.timer1.Interval = 2000; //every 2 seconds
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
timer1.Enabled = true;
Helper.ServiceStartLog("Test window service started");
}
private void timer1_Tick (object sender, ElapsedEventArgs e)
{
PDFHelper.WriteErrorLog("Timer ticker and Log Running Job is Running");
}
protected override void OnStop()
{
timer1.Enabled = false;
Helper.WriteErrorLog("Test window service stopped");
}
}
}
Program.cs的樣子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TestWindowsService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
Scheduler myservice = new Scheduler();
myservice.onDebug();
Thread.Sleep(Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Scheduler()
};
ServiceBase.Run(ServicesToRun);
#endif
}
}
}
助手類是什麼樣子
using System;
using System.IO;
using System.Threading;
namespace TestWindowsService
{
public static class Helper
{
public static void ServiceStartLog(string Message)
{
try
{
StreamWriter sw = null;
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\logFile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
sw.Flush();
sw.Close();
}
catch (Exception ex1)
{
Console.WriteLine(ex1.Message.ToString());
}
}
public static void WriteErrorLog(string Message)
{
try
{
StreamWriter sw = null;
Thread.Sleep(5000);
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\logFile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
sw.Flush();
sw.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
}
}
哦很酷。讓我試試你的解決方案。 – ProgSky
按預期工作!謝謝 ! – ProgSky