我有一种情况,我应该通过Windows服务和Timer.Here解决这个问题。我有一个winform,用户可以在这里添加他想要报告的时间。他将添加的时间将是什么时候保存到database.Now,因为这意味着多个用户,所以在数据库中将有多个相同的添加。现在根据我的要求,我必须向用户发送由他设置的特定时间的报告。我必须设置我的计时器,以便每当来自数据库的适当时间到来时,应该将报告发送给用户。之后它应该再次发送并发送它等等。 为此,我正在使用Windows服务并尝试通过执行数据库连接和查询来第一次获取我们需要设置计时器。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using MySql.Data.MySqlClient;
namespace AutomailTrigger
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
public void OnDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
string time;
string conn = "Server=localhost;Port=3306;Database=;UID=root;Pwd=;pooling=false";
string Query = "SELECT * FROM `reportsetting` order by SendingTime desc limit 1;";
MySqlConnection con = new MySqlConnection(conn);
MySqlCommand comm = new MySqlCommand(Query, con);
con.Open();
MySqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
time = dr["time"].ToString();
}
this.timer = new System.Timers.Timer();
// Hook up the Elapsed event for the timer.
this.timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
this.timer.Enabled = true;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Your code when the timer elapses
}
protected override void OnStop()
{
}
}
}
现在我有一个查询如何在此添加计时器以保持循环移动.. 请帮忙,因为这对我来说是合乎逻辑的障碍..
答案 0 :(得分:2)
你可以创建一个如下所示的计时器,当你说它来自数据库时,它会从数据库中收集计时器经过的时间,每当时间过去你就可以完成你的过程: -
var timer = new System.Timers.Timer("(Take time from database or use static time)");
// Hook up the Elapsed event for the timer.
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Enabled = true;
...
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Your code when the timer elapses
}
更新: -
/// <summary>
/// Your Timer.
/// </summary>
private System.Timers.Timer timer;
protected override void OnStart(string[] args)
{
this.timer = new System.Timers.Timer("(Take time from database or use static time)");
// Hook up the Elapsed event for the timer.
this.timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
this.timer.Enabled = true;
string conn = "Server=localhost;Port=3306;Database=;UID=root;Pwd=;pooling=false";
string Query = "SELECT * FROM `reportsetting` order by SendingTime desc limit 1;";
MySqlConnection con = new MySqlConnection(conn);
MySqlCommand comm = new MySqlCommand(Query, con);
con.Open();
MySqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
}
}
protected override void OnStop()
{
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Your code when the timer elapses
}