我有一個問題,我試圖創建一個服務來連接到我創建的API。每1小時訪問數據庫C#
此服務必須每小時連接到Mysql中的數據庫,並查看是否有一定的值。
例如每次我會看到字段x是否具有值y。如果是真的,將不得不運行一些東西。
我已經閱讀了一些關於線程和System.Threading.Timer的內容,但是不太明白,有人能給我一個實際的例子或正確的方式來做到這一點,請問我在找什麼?
在此先感謝..
我有一個問題,我試圖創建一個服務來連接到我創建的API。每1小時訪問數據庫C#
此服務必須每小時連接到Mysql中的數據庫,並查看是否有一定的值。
例如每次我會看到字段x是否具有值y。如果是真的,將不得不運行一些東西。
我已經閱讀了一些關於線程和System.Threading.Timer的內容,但是不太明白,有人能給我一個實際的例子或正確的方式來做到這一點,請問我在找什麼?
在此先感謝..
創建一個簡單的程序,它您需要什麼,運行它運行在每個小時windows task。
創建一個Windows服務,並給它一個1小時的時間間隔。此Windows服務將始終運行,但會按指定的時間間隔向數據庫發出查詢。與Windows服務,你不必亂七八糟的線程和所有。
partial class YourService : ServiceBase
{
Timer timer = new Timer();
...
...
public YourService()
{
InitializeComponent();
}
/// <summary>
///
protected override void OnStart(string[] args)
{
timer.Interval = 1000000; /*The interval of the Windows Service Cycle set this to one hour*/
timer.Start();
timer.Enabled = true;
timer.AutoReset = true;
timer.Elapsed += new ElapsedEventHandler(OnElapseTime); /*fire the event after each cycle*/
}
private void OnElapseTime(object sender, ElapsedEventArgs e)
{
// HERE DO UR DATABASE QUERY AND ALL
}
...
...
}
創建一個Windows服務並將其移動到您擁有該應用程序的服務器。這個Windows服務將每天24小時運行,並且會滿足您的要求。
class Program:ServiceBase { System.Timers.Timer timer;
static void Main(string[] args)
{
ServiceBase.Run(new Program());
}
public Program()
{
this.ServiceName = "DB Sync";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
InitializeTimer();
}
protected override void OnStop()
{
base.OnStop();
}
protected void InitializeTimer()
{
try
{
if (timer == null)
{
timer = new System.Timers.Timer();
timer.Enabled = true;
timer.AutoReset = true;
timer.Interval = 60000 * 1;
timer.Enabled = true;
timer.Elapsed += timer_Elapsed;
}
}
catch (Exception ex)
{
}
finally
{
}
}
protected void timer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
{
TimerTick();
timer.Interval = 60000 * Convert.ToDouble(ConfigurationManager.AppSettings["TimerInerval"]);
}
private void TimerTick()
{
try
{
// Query the DB in this place.
}
catch (Exception ex)
{
}
}
}
同意。對於這種情況,服務可能會過度。 Windows任務可能是更好的方法。 – Simon 2013-04-29 09:11:35