-1

How can I execute a C# method every 40 seconds continuously?

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135

4 Answers4

5

You should use the Timer functionality available in .net

Documentation

Here's the code from MSDN, with slight changes.

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {

        // Create a timer with a fourty second interval.
        aTimer = new System.Timers.Timer(40000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);    


        // If the timer is declared in a long-running method, use 
        // KeepAlive to prevent garbage collection from occurring 
        // before the method ends. 
        //GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is  
    // raised. 
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        //Code that needs repeating every fourty seconds
    }
}
Ryan McDonough
  • 9,732
  • 3
  • 55
  • 76
  • I've been told to not answer with links ;) – makim Aug 08 '13 at 10:14
  • 6
    It's far better to use `System.Threading.Timer`, as the one you link too can swallow exceptions. – Moo-Juice Aug 08 '13 at 10:16
  • I based my answer based on what he's likely to understand, since he can't google "run function every 40 seconds c#" (which is every 2 seconds but close enough) and click on the first link - I assumed threading might be a reach. But @Moo-Juice you're right, it's a much better implementation. – Ryan McDonough Aug 08 '13 at 10:21
  • 1
    Should be 40000 and not 4000 – Adi Lester Aug 08 '13 at 10:27
2

Have a look at System.Threading.Timer

var timer = new System.Threading.Timer(new TimerCallback(YourMethod), null, 40000, Timeout.Infinite);
private void YourMethod(object state)
{
    //Magic
    timer.Change(40000, Timeout.Infinite);
}
makim
  • 3,154
  • 4
  • 30
  • 49
  • yes the timer starts after 40 seconds but it has not been asked to start immediately and the timer run´s after every 40seconds try it out timer.Change(40000, Timeout.Infinite) resets the Timer and it will run again ;) – makim Aug 08 '13 at 10:30
  • Ah, didn't know that. Have changed vote :) This answer is the more preferable one then, as it uses `System.Threading.Timer`. – Moo-Juice Aug 08 '13 at 11:06
1

Try this

<asp:UpdatePanel runat="server" UpdateMode="Always">
    <ContentTemplate>
    <asp:Timer  ID="timer" runat="server" Interval="40000"></asp:Timer>
    </ContentTemplate>
</asp:UpdatePanel>

in code behind

    protected void Page_Load(object sender, EventArgs e)
    {
       callyourfunction();
     }
sangram parmar
  • 8,462
  • 2
  • 23
  • 47
0

I could suggest using Quartz.Net for this. You can implement an Service that is scheduled with Quartz.Net. You'll only need to configure your trigger the way you want.

Luiz
  • 542
  • 5
  • 10