ASP.Net Scheduled Task Executing Method by Multiples

Credit to the author from this site:

https://codinginfinite.com/creating-scheduler-task-seconds-minutes-hours-days/

I can define the task execution parameter in 24hr time to run my method, but I see no logic in the code that is clear to me as to why it fires my method by a large multiplicity of times. The issue is that where my method should be executed only but once per minute starting at the specified time, it is actually executed 20+ times in less than one minute. I’ve tried altering parameters and repeat intervals, but nothing seems to resolve the issue and different execution intervals always fire the method many times over than what is specified – i.e. similarly, 5min interval, but I get 30+ order placements within one minute whereas I would expect not more than one order execution every 5 minutes..

Any ideas on why this could be happening with this code?

Here is the service class:

public class SchedulerService
    {                
        private static SchedulerService _instance;
        private List<Timer> timers = new List<Timer>();
        private SchedulerService() { }
        public static SchedulerService Instance => _instance ?? (_instance = new SchedulerService());
        public void ScheduleTask(int hour, int min, double intervalInHour, Action task)
        {            
            DateTime now = DateTime.Now;
            DateTime firstRun = new DateTime(now.Year, now.Month, now.Day, hour, min, 0, 0);

            if (now > firstRun)
            {
                firstRun = firstRun.AddDays(1);
            }
            
            TimeSpan timeToGo = firstRun - now;
            if (timeToGo <= TimeSpan.Zero)
            {
                timeToGo = TimeSpan.Zero;
            }   
            
            var timer = new Timer(x =>
            {
                task.Invoke();
            }, null, timeToGo, TimeSpan.FromHours(intervalInHour));
            timers.Add(timer);            
        }
    }

Here is the scheduler class:
public class Scheduler
    {
        public static void IntervalInSeconds(int hour, int sec, double interval, Action task)
        {
            interval = interval / 3600;
            SchedulerService.Instance.ScheduleTask(hour, sec, interval, task);
        }
        public static void IntervalInMinutes(int hour, int min, double interval, Action task)
        {
            interval = interval / 60;
            SchedulerService.Instance.ScheduleTask(hour, min, interval, task);
        }
        public static void IntervalInHours(int hour, int min, double interval, Action task)
        {
            SchedulerService.Instance.ScheduleTask(hour, min, interval, task);
        }
        public static void IntervalInDays(int hour, int min, double interval, Action task)
        {
            interval = interval * 24;
            SchedulerService.Instance.ScheduleTask(hour, min, interval, task);
        }
    }

Instantiated on page load with defined start time parameters and repeat interval:
    protected void Page_Load(object sender, EventArgs e)
    {
        Scheduler.IntervalInMinutes(20, 15, 1,
        () => {
            buyOrder();
        });
    }

At 20:15, call this method and repeat every minute:
    private static void buyOrder()
    {
        //This is only a basic POST method
    }

Result:

I get the multiplicity of orders executed in <1min as mentioned.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The issue appears not to be in the code but rather the fact that you are running the scheduling instruction in the Page_Load event.

My educated guess is if you debug this, you will find that your Page_Load event is firing multiple times which causes multiple jobs to be scheduled.

There are a number of reasons why this could happen (like multiple event handlers, Ajax requests, or even the act of debugging through the code itself as some browsers will reissue requests if they don’t receive a timely response) but the bottom line is you should rethink how/where you trigger the scheduling.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x