我遇到了问题,我正在尝试创建一个连接到我创建的API的服务。
此服务必须每小时连接到Mysql中的数据库,并查看是否存在某个值。
例如,每次我看到字段x的值是否为y。如果是真的,就必须运行一些东西。
我已经阅读了一些关于Threads和System.Threading.Timer的内容,但是我不太明白,有人可以给我一些实际的例子或者正确的方法吗,我正在寻找什么呢?
提前致谢..
答案 0 :(得分:7)
创建一个简单的程序,它可以满足您的需求,并以每小时运行的windows task运行。
答案 1 :(得分:1)
创建一个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
}
...
...
}
答案 2 :(得分:0)
创建一个Windows服务并将其移动到您拥有该应用程序的服务器。这个Windows服务将每天24小时运行,并满足您的要求。
类程序:ServiceBase { System.Timers.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)
{
}
}
}