Custom Timed Events

From AbleCommerce Wiki
Jump to: navigation, search

You can set up custom code to run on a periodic basis for your AbleCommerce store. Below is sample code that would be placed inside the global.asax file. It links into the Application Start event to set up a system timer. If you have your application running inside a web garden, be aware that this timer will be created once for each process.

This sample runs every ten seconds. The Logger statements are not necessary. They are in place so you can monitor the app_data/app.log file to confirm that your task is running.

    // THIS VARIABLE HOLDS THE TIMER
    private System.Threading.Timer timer;

    protected void Application_Start(object sender, EventArgs e)
    {
        Logger.Info("Application Starting");
        // SPECIFY THE NUMBER OF MILLISECONDS THAT THE TIMER WILL REPEAT
        int intervalMilliseconds = 10000;
        // THIS SETS UP THE TIMER
        timer = new System.Threading.Timer(new System.Threading.TimerCallback(TimedEvent), null, intervalMilliseconds, intervalMilliseconds);
    }

    protected void Application_End(object sender, EventArgs e)
    {
        Logger.Info("Application Ending");
        if (timer != null) timer.Dispose();
    }

[[Category:AbleCommerce 7]]
    private void TimedEvent(object stateInfo)
    {
        // THIS IS RUNNING ON ITS OWN THREAD, OUTSIDE OF HTTPCONTEXT
        // (HTTPCONTEXT.CONTEXT IS NULL)
        // YOU MUST INITIALIZE THE TOKEN FOR THE STORE, CHANGE THE ID IF IT IS OTHER THAN 1
        Store store = StoreDataSource.Load(1);
        // INITIALIZE THE TOKEN FOR THIS STORE
        Token.Instance.InitStoreContext(store);
	// *********
        // PUT YOUR CODE BELOW THIS COMMENT
	// *********
        Logger.Info("Timed task is running...");
	// *********
        // PUT YOUR CODE ABOVE THIS COMMENT
	// *********
        // RESET THE TOKEN INSTANCE AFTER THE EVENT RUNS
        Token.ResetInstance();
    }