c#中的线程以1分钟的服务器时间间隔执行

时间:2014-03-06 11:17:04

标签: c# asp.net multithreading

我在c#应用程序中创建了一个线程。它的代码如下。

[WebMethod]
public void start()
{
    Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
    thread.Start();
}
[WebMethod]
public void stop()
{
    Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
    thread.Abort();
}
public void WorkThreadFunction()
{
    try
    {


            TimeZone zone = TimeZone.CurrentTimeZone;
            DateTime dt = DateTime.Now.AddHours(12);
            dt = dt.AddMinutes(30);
            TimeSpan offset = zone.GetUtcOffset(DateTime.Now);
            String s = "insert into tb_log(timestamp) values('" + dt + "')";
            Class1 obj = new Class1();
            string res = obj.executequery(s);


    }
    catch
    {
    }
}

当我运行此代码时,该值只会一次输入到表中。我需要在一天,一周和一年中以1分钟的间隔执行此线程。如何使这成为可能?如果我写的代码是正确的,也要纠正我。我是c#中线程的新手。所以有人请帮助我。谢谢和问候..

4 个答案:

答案 0 :(得分:1)

public WebServiceClass : WebService
{
    private boolean terminated = false;
    private boolean running = false;

    [WebMethod]
    public void start()
    {
        if (running)
        {
            //Already Running!
        }
        else
        {
            running = true;
            terminated = false;
            //Start a new thread to run at the requested interval
            Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
            thread.Start();
        }
    }

    [WebMethod]
    public void stop()
    {
        //tell the thread to stop running after it has completed it's current loop
        terminated  = true;
    }

    public void WorkThreadFunction()
    {
        try
        {
            DateTime nextLoopStart = DateTime.Now;
            while (!terminated)
            {
                TimeZone zone = TimeZone.CurrentTimeZone;
                DateTime dt = DateTime.Now.AddHours(12);
                dt = dt.AddMinutes(30);
                TimeSpan offset = zone.GetUtcOffset(DateTime.Now);
                String s = "insert into tb_log(timestamp) values('" + dt + "')";
                Class1 obj = new Class1();
                string res = obj.executequery(s);    

                while (DateTime.Now < nextLoopStart)
                {
                    System.Threading.Thread.Sleep(100);
                }    
                nextLoopStart += new TimeSpan(0,1,0);
            }
            //Reset terminated so that the host class knows the thread is no longer running

        }
        catch (ThreadAbortException)
        {
            //LogWarning("INFO: Thread aborted");
        }
        catch (Exception e)
        {
            //LogError("Error in Execute: " + e.Message);
        }
        finally
        {
            running = false;
        }
    }
}

答案 1 :(得分:0)

尝试以下更新

public class myApp
{   
    public System.Diagnostics.EventLog myEventLog { get; set; }
    private Thread appThread;
    public int TimerIntervalSeconds {get; set;}

    public void Start()
    {

        appThread = new Thread(new ThreadStart(WorkThreadFunction));
        appThread.Start();
    }

    public void Stop()
    {
        if (appThread != null)
        {
            appThread.Abort();
            appThread.Join();
        }
    }
    private void WorkThreadFunction()
    {
        // Loop until the thread gets aborted
        try
        {
            while (true)
            {
                WriteToDatabase();

                // Sleep for TimerIntervalSeconds
                Thread.Sleep(TimerIntervalSeconds * 1000);
            }
        }
        catch (ThreadAbortException)
        {
            myEventLog.WriteEntry("INFO: Thread aborted", System.Diagnostics.EventLogEntryType.Warning);
        }
        catch (Exception e)
        {
            myEventLog.WriteEntry("Error in Execute: " + e.Message, System.Diagnostics.EventLogEntryType.Error);
        }
    }
}

这是完整的&#39;类。请致电Start将其关闭,然后Stop结束。将TimerIntervalSeconds设置为您希望事件发生的频率。

我最初没有时间给出整个解决方案。

答案 2 :(得分:0)

我会在C#中使用Timer类。我不熟悉ASP.NET,但我认为以下链接会有所帮助。 http://msdn.microsoft.com/en-us/library/system.web.ui.timer(v=vs.110).aspx

创建计时器的实例,设置经过的时间(以毫秒为单位)并将方法附加到计时器的tick事件。然后在每x毫秒后调用此方法。

编辑:要在另一个线程上运行任务,请将其作为任务运行(.NET 4.0或更高版本)

timer.tick + =(s,e)=&gt; {

TaskFactory.StartNew(()=&gt; WorkThreadFunction());

};

请注意,为简单起见,忽略了异常处理。

答案 3 :(得分:0)

对于一个简单的解决方案,我会使用Timer类。 实际上.NET中有3个Timer类,所以它取决于你的用途。最常见的是 - System.Threading.Timer

对于更强大和完整的解决方案,我会使用时序框架,例如Quartz.NET http://www.quartz-scheduler.net/

这完全取决于您的具体需求。