简体   繁体   中英

C# scheduled task attributed methods in a .NET assembly

I often find when I'm writing a service class (within an ASP.NET app) that in addition to the usual method calls, I'd like scheduled method calls which invoke, say, every day at 1am.

My idea is to create a custom attribute which would be used against any scheduled task methods:

[ScheduledTask(Every=TimeSpans.Day, At=6)]
public static void Cleanup()
{
    // some clean up code here
}

In order to implement this, I would have to scan the assemblies loaded in the AppDomain at the web app's Application_Start method. Look for static methods with the ScheduledTask attribute and then invoke the scheduler to run these methods according to the attribute.

I've looked around the net and found that no-one else seems to have done this and wondered whether this is generally a bad idea for some reason!? Would it be possible do you think?

thanks!

Some problems I see:

  • Separation of concerns. Your class provides the Cleanup implementation and the schedule to run it. An administrator is likely to want to control the schedule (eg run Cleanup at times of low activity), so it's more common to use configuration to provide a schedule.

  • Difficult for an administrator to get an overview of what tasks are scheduled.

  • Interpretation of the schedule. Is your example 6 UTC or local time?

  • Ease of modification of the schedule - you need to recompile.

  • ASP.NET applications can shut down, eg after a period of inactivity, or on a predefined schedule, and won't start up again until another request arrives. Which makes IIS a poor host for running scheduled tasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM