How to call a method after so many seconds?

后端 未结 5 842
太阳男子
太阳男子 2020-12-06 22:31

In my project I would like to be able to call a method after 3 minutes have passed. There is no \"main loop\" to speak of so I cannot use a stopwatch and constantly check if

相关标签:
5条回答
  • 2020-12-06 23:00

    After trying out several options, the method was not self-triggering. Hence, I used Javascript to solve the same problem as shown below.

    <script>
    function Timer() {
        $.ajax({
            url: "@Url.Action("Timer", "Exam")",//Method to call. Timer Method in Exam Controller
            type: 'GET', // <-- make a async request by GET
        dataType: 'html', // <-- to expect an html response
        cache: false,
        async: true
        });
    }
    setInterval(function () { Timer(); }, 5000);//Triggers method Timer() after 5 seconds
    </script>
    
    0 讨论(0)
  • 2020-12-06 23:15

    I really believe your idea with the Timer object is the right way to go. It sounds like you're familiar with how to use it - but here's an example:

        aTimer = new System.Timers.Timer(1000 * 60 * 3);
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Enabled = true; 
    

    http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

    0 讨论(0)
  • 2020-12-06 23:20

    Use a Timer.

    While there will be a slight overhead if you create a 1000 timers, it won't be too much. Timers will do their job and fire an event when 3 minutes have passed. Also, if you want your code to repeat every 3 minutes, Timers are the way to go.

    0 讨论(0)
  • 2020-12-06 23:21

    Timer is not a good solution for hundreds/thousands, as Timers are a limited resource.

    Are all the methods to be called from the same application?

    If so, I would create a small stub class that had a datetime, and an Action, and add delegates to the method to be called, along with the target time. Then in a background thread loop through the list and call the delegates when appropriate (and remove them obviously)

    An alternate solution would be to do something like QueueUserWorkItem for each method to be called, and first thing in the thread sleep for the appropriate amount of time until the method should be called.

    For all solutions (mine and others), be aware of any marshaling you have to do if you are interacting with the GUI, or any locking that may need to be done to avoid threading concurrency issues

    0 讨论(0)
  • 2020-12-06 23:23

    if you have hundreds or thousand of those timers, some scheduling will do the job.

    You really should investigate quartznet

    lots of concurrent timers perform not very well as i experienced, quartznet will do.

    and if you really want to have those scheduling tasks in your application, perhaps this article gives you some ideas Task Scheduler Class Library for .NET

    0 讨论(0)
提交回复
热议问题