www.webdeveloper.com
Results 1 to 8 of 8

Thread: [NEW] Run function once hour after specific time

  1. #1
    Join Date
    Nov 2013
    Posts
    41

    Post [NEW] Run function once hour after specific time

    I know I made a previous post, on this, but I hasn't been working correctly.

    I want to run a function (weatherForecast_Update) one hour after the given time (forecast_loaded). I am getting the correct time in weatherForecast_Update_time in milliseconds*, but the timeout runs continuously. MomentJS is working perfectly, and if the corrected code could use it, that would be great.

    So I have this code:
    Code:
    var forecast_loaded = "2013-11-14T19:31:39-06:00";
    
    moment_now = moment(new Date());
    moment_forecastloaded_add1h = moment(forecast_loaded).add('h', 1);
    var weatherForecast_Update_time = moment_forecastloaded_add1h.valueOf() - moment_now.valueOf();
    
    console.log(weatherForecast_Update_time);
    
    if (moment_weatherForecast_Update_time > 0) {
         //setTimeout(weatherForecast_Update(), weatherForecast_Update_time);
    }
    I commented out the setTimeout because it will run too often and freeze up your browser (when testing it). It gives a "stack size exceeded" error.

    Thanks for any help! (great forum )

    *Note: You can easily convert time and other units with Google by typing Xms in min where X is the time, ms is the current unit (in this case milliseconds) and min is the target unit (in this case minutes). The answer will even pop up in the suggestions!
    Last edited by DaAwesomeP; 11-14-2013 at 08:00 PM. Reason: Added Note on conversions with Google

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,294
    To run a function onload and then once per hour thereafter, you need to first off have a starting reference... Then set an interval timer

    Goes something like this....


    Code:
    one_hour_of_milliseconds = 60*60*1000; // minutes * seconds * milliseconds
    interval = setInterval( "functionToCall()", one_hour_of_milliseconds );
    The interval timer will call the function every hour until the browser is closed.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  3. #3
    Join Date
    Nov 2013
    Posts
    41
    I guess I didn't explain this very well. I want to run the function one hour after the given time. I have a library that gets and caches NOAA weather Forecasts once per hour (suggested by NOAA). The function this triggers loads the new forecasts with AJAX. Instead of updating it one hour after page load, I would prefer to update it one hour after the forecast was fetched. That time is forecast_loaded. The code above is just an example of the timestamps it outputs. I would prefer to use MomentJS (it processes it fine and keeps it neat), but I can alter the PHP Date() if needed.

  4. #4
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,294
    When the page loads, the function will get called one hour after.

    If you are setting a time when the page is called, then its simply a case of adding one hour of milliseconds to a figure from a time function like so.


    Code:
    page_loaded_time = new Date( "<?php echo $your_date_string_from_php; ?>" ).getTime();
    
    one_hour_of_milliseconds = 60*60*1000; // minutes * seconds * milliseconds
    
    interval = setInterval( "functionToCall()", one_hour_of_milliseconds + page_loaded_time );
    I figured you were having the time reference added in and thought that you could have worked out that all you needed to do was add milliseconds to a time reference that can be used to return milliseconds. Simple math really.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  5. #5
    Join Date
    Nov 2013
    Posts
    41
    Err... OK, so forecast_loaded is a completely different time than the page load. The page load is moment_now. If I access the page a 5:30 PM, and the forecast was last updated at 5:00 PM, then it should update in 30 minutes, as that is one hour since 5:00 PM (it would update at 6:00 PM). The forecast_loaded is converted to milliseconds since the Unix Epoch, which is why I am have moment_now subtracted from moment_forecastloaded_add1h (I am adding one hour with MomentJs). So, I am adding 1hr to the forecast load time. I am then subtracting the current time from it to get the amount of time until it needs to reload again. I then check to make sure it is positive so that I don't have infinite loads.

    Sorry I've been vague.
    Last edited by DaAwesomeP; 11-15-2013 at 09:09 PM.

  6. #6
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    795
    Don't know if the timezone offset was needed:

    Code:
    var
    	forecast_loaded = '2013-11-17 01:07:00',
    	i, j;
    
    function weatherForecast_Update()
    {
    	alert('UPDATE WEATHER FORECAST');
    }
    
    if (i = /^(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)/.exec(forecast_loaded)) {
    	if ((j = ((new Date(i[1], i[2] - 1, i[3], i[4], i[5], i[6]).getTime()) + 3600000) - (new Date().getTime())) > 0) {
    		setTimeout(weatherForecast_Update, j);
    	}
    }
    Note: If the update period has already lapsed then the script won't run the update function. (I saw that's how you had it in the original version)

    -------------

    If forecast_loaded can be given the last update time as a unix timestamp, then the script could be a whole lot shorter, example:

    Code:
    var
    	forecast_loaded = 1384650420,
    	i;
    
    function weatherForecast_Update()
    {
    	alert('UPDATE WEATHER FORECAST');
    }
    
    if ((i = (new Date((forecast_loaded + 3600) * 1000).getTime()) - (new Date().getTime())) > 0) {
    	setTimeout(weatherForecast_Update, i);
    }
    Last edited by bionoid; 11-16-2013 at 06:30 PM.
    JavaScript: Learn | Validate | Compact | bionoid

  7. #7
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,294
    Quote Originally Posted by DaAwesomeP View Post
    Err... OK, so forecast_loaded is a completely different time than the page load. The page load is moment_now. If I access the page a 5:30 PM, and the forecast was last updated at 5:00 PM, then it should update in 30 minutes, as that is one hour since 5:00 PM (it would update at 6:00 PM). The forecast_loaded is converted to milliseconds since the Unix Epoch, which is why I am have moment_now subtracted from moment_forecastloaded_add1h (I am adding one hour with MomentJs). So, I am adding 1hr to the forecast load time. I am then subtracting the current time from it to get the amount of time until it needs to reload again. I then check to make sure it is positive so that I don't have infinite loads.

    Sorry I've been vague.
    Which is why you get the date and time from PHP that has been provided with the time you want.

    These things are fairly simple to do and shouldn't have to keep on sign posting the way for you.

    In a nutshell...

    your time you want for your forecast, its its 5.30 in the morning then make that string 5.30 in the morning.

    this is written in to the previously illustrated in the code I showed

    Bobs your Uncle... (and your father too.)

    Simples.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  8. #8
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,294
    Ok, holding your hand here, this function I wrote, and tested as a POC will run in background of your site code, it is an adaptation of a clock I made for timing purposes.

    PHP Code:
    <?php

        
    // get a timezone offset for testing
        
    date_default_timezone_set("Europe/London");
            
        
    // in the format of 2013-11-14T19:31:39-06:00
        // ISO 8601 date 
        
    $lastReport =  "2013-11-17T15:45:39-00:00"// date format of last weather issued

    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Now and Then</title>
    <script>
    time = {
        lastUpdate:new Date("<?php echo $lastReport;?>").getTime(),
        now:0,
        ref:0,
        diff:0,
        oneHour:3600000,
        tick:function(){
            // get the time now
            this.ref = !this.ref?new Date(time.lastUpdate).getTime():this.ref;
            this.now = new Date().getTime();
            // set the difference from the time ref of last update
            this.diff = Math.floor( (this.now - this.ref)/1000 ) * 1000;
            
            if(this.diff>=0){
            
                this.ref += this.oneHour; // add an hour to the next update
        
                /* MAKE STUFF HAPPEN */
            
            }
        },
        auto:setInterval("time.tick()",1000)
    }



    </script>
    </head>

    <body>
    </body>
    </html>
    In short, where it says /* MAKE STUFF HAPPEN */ is the area you put your function that you want to run, the clock as I said runs and counts down to 0, after 0 the hour of milliseconds gets added and it begins countdown to next whatever you want.

    Runs hourly from whenever the $lastReport is set to, you will have to research your timezone setting on the PHP side of things.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles