Delayed execution of background task (temporal event)

Hi, I am trying to create a datafield that fetches data from an HTTP server. I have followed some examples published here on the forum and has created a datafield that fires off a background process (every 5 mins) to connect to the web server. It works good

However, I would like it to run the background process instantly when i start/initiate the datafield. Now it takes up to 5 mins before it executes the background process. Is there a way to get the background process to execute immediately? 

I'm using the registerFor TempralEvent call in the getInitialView function:

function getInitialView() {
    	
    	var url = (App.getApp()).getProperty("Url");
    	//debug
    	Sys.println("URL = "+(App.getApp()).getProperty("Url"));
    	
    	if((Toybox.System has :ServiceDelegate) && (url != null) && !url.equals("")) {
    		canDoBG=true;
    		
    		//remove any previously registered events
    		Background.deleteTemporalEvent();
        	
        	Background.registerForTemporalEvent(new Time.Duration(5 * 60));

    	}

Any ideas appreciated, thanks!

/Fredrik

  • The key here is to delete the temporal event when your data field exits, so the next time it's registered it runs right away.  This is something you may want to do in general with a data field, as you really don't want the background to run if the the DF isn't being used.

    A good place to do this is in onStop(), but there's a trick, as onStop is also run when the background itself exits, so you need to know if you're in the main app or the background.

    What I do, is in my AppBase, I have

    var inBackground=false;

    and then in getServiceDelegate,

    inBackground=true;

    getServiceDelegate is only called by the background, and the main app and background have their own copy of the variables, so this only sets the background's "inBackground".

    Then in onStop(), check it.

    function onStop(state) {

      if(!inBackground) {Background.deleteTemporalEvent();}

    ....

    }

  • Thank you Jim, it works perfect!!!!!

  • Hi Jim! I stumbled upon this today. Would onStop() be better than onReset(). The issue with onStop() is that you can Stop and Start your activity multiple times. Some people use STOP instead of AutoPause to control when to manually pause an activity. But onReset() is generally called after the final STOP upon SAVE or DISCARD. Which should be a better indication of the end of that activity.

  • I think you confuse the application and the datafield lifecycle. The stop and reset you are reffering to (from a user's prospective) are called: Datafield.{onTimerStart,onTimerStop,onTimerPause,onTimerResume,onTimerReset, ...} and there's the AppBase.onStop. 

  • Yes, onStop() in the AppBase.  NOT onTimerStop()