Recent Articles

Creating a Scheduled Task in DotNetNuke

In DotNetNuke, you can easily create a scheduled task to do whatever you want (eg. clean up files, check currency, etc) easily without needing to write a windows service or using the Windows Task Scheduler. This is quite handy if you want to keep everything self contained or you run within a hosting environment that don't allow you access to Remote Desktop.

To begin, simply create a class that inherits from DotNetNuke.Services.Scheduling.SchedulerClient. Add a constructor that takes a ScheduleHistoryItem argument and calls the base() constructor. Override the DoWork() method and perform your work there. Remember to catch exception and set ScheduleHistoryItem.Succeeded = true on success.

public class CurrencyAgent : SchedulerClient
 {
  public CurrencyAgent(ScheduleHistoryItem scheduleHistoryItem):base()
  {
   this.ScheduleHistoryItem = scheduleHistoryItem;
  }

  public override void DoWork()
  {
   try
   {
        // Do some work, like download today's currency...

        // Notify that scheduled succeede
        ScheduleHistoryItem.Succeeded = true;
   }
   catch (Exception ex)
   {
    // report a failure
    ScheduleHistoryItem.Succeeded = false;

    // log the exception into
    // the scheduler framework
    ScheduleHistoryItem.AddLogNote("EXCEPTION: " + ex.ToString());

    // call the Errored method
    Errored(ref ex);

    // log the exception into the DNN core
    Exceptions.LogException(ex);

   }
  }
 }

Compile the code into a normal DLL and deploy it with your module. Go to Host > Schedule and add your scheduler. You'll be asked to provide the full class name and assembly. DotNetNuke can run the scheduled task under ASP.NET request thread or on a separate timer thread of its own. If configured to run on a timer thread, beware that your code won't have access to ASP.NET variables and environment.