...

View Full Version : Playing Script on a certain time



Maestro
07-14-2010, 05:37 PM
Suppose I have some function ... myFunction();
And I want it to be executed from 3am - 11pm but not at any other time
So far what i had done is along the line of



for(i=0;i<99999;i++)
{
var time = new Date();
var hours = time.getHours();
if (hours>=3 && hours<=23){
myFunction();
}
}

What happens so far is that:

If it is the right time it loops over and over and continually executes the function (which is what I want)

If it's the wrong time (not 3am-11pm) it loops once, doesn't execute the functoin and then the script finishes (whereas I want it to continue looping until the right time comes along)

If its the right time and then it moves to the wrong time it stops looping, whereas i want it to not execute the function but continue looping until the right time comes around again.


So the overall affect is that at the given times of day the script plays and when its not the correct time it doesnt and then when it is the right time again it starts playing again, seemlessly and continually

mrhoo
07-14-2010, 07:15 PM
You could pass the function and its time limits to a scheduler.

If the current local time is after the start and before the end limit, return the function.

Otherwise, find the next start time.
If the current time is greater than the end limit,
the next start time will be the next day.

When you have the next start time, subtract the current time from it to get the milliseconds difference.

Use the difference to set a timeout, the function will be called after the correct interval
(when the current time reaches the next start time).

If you pass the start and end limits as arrays, you can schedule to the minute.



function timeSlot(fun, start, end){
var diff, playstart= new Date(),
playend= new Date(), now= new Date();

for(var i= 0; i<4; i++){
if(start[i]== undefined) start[i]= 0;
if(end[i]== undefined) end[i]= 0;
}
playstart.setHours.apply(playstart, start);
playend.setHours.apply(playend, end);

if(playstart<= now && playend>= now) return fun();

if(playend< now && playstart.getDate()== now.getDate()){
playstart.setDate(playstart.getDate()+1);
playEnd.setDate(playend.getDate()+1);
}
setTimeout(diff,playstart- now);
}

//test function

function announce(){
alert(new Date().toLocaleDateString());
}

//test
timeSlot(announce, [3, 0], [23, 0]);

If all you need are hours, pass integers:

function timeSlot(fun, start, end){
var diff, playstart= new Date(),
playend= new Date(), now= new Date();
playstart.setHours( start);
playend.setHours(end);
if(playstart<= now && playend>= now) return fun();
if(playend< now && playstart.getDate()== now.getDate()){
playstart.setDate(playstart.getDate()+1);
}
setTimeout(diff,playstart- now);
}
//test2
timeSlot(announce, 3, 23);

Maestro
07-15-2010, 04:25 PM
Worked a charm, many thanks!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum