Search code examples
javascriptgreasemonkeyuserscripts

Create a scheduled Greasemonkey script


I need to create a special kind of script.
I want to show a message at certain times of the day. I've tested the code in Firebug Console and it works. The code is:

//Getting the hour minute and seconds of current time
var nowHours = new Date().getHours() + '';
var nowMinutes = new Date().getMinutes() + '';
var nowSeconds = new Date().getSeconds() + '';

var this_event = nowHours + nowMinutes + nowSeconds;
//172735 = 4PM 25 Minutes 30 Seconds. Just checked if now is the time
    if (this_event == "162530") {
        window.alert("Its Time!");
    }

I feel that the Script is not running every second. For this to work effectively, the script has to be able to check the hour minutes and second "Every Second". I'm not worried about the performance, I just have to be accurate about the timing (to the second).

How do I do this?


Solution

  • Of course the script isn't running each second, GM-scripts run once when the document has been loaded.

    Calculate the difference between the current time and the target-time and use a timeout based on the difference:

    var now=new Date(),
        then=new Date(),
        diff;
        then.setHours(16);
        then.setMinutes(15);
        then.setSeconds(30);
        diff=then.getTime()-now.getTime();
    
        //when time already has been reached
        if(diff<=0){
          window.alert('you\'re late');
        }
        //start a timer
        else{
         window.setTimeout(function(){window.alert('it\'s time');},diff);
        }