Start a Function at Given Time

Start a Function at Given Time

Reading the docs from http://docs.python.org/py3k/library/sched.html:

Going from that we need to work out a delay (in seconds)...

from datetime import datetime
now = datetime.now()

Then use datetime.strptime to parse '2012-07-17 15:50:00' (I'll leave the format string to you)

# I'm just creating a datetime in 3 hours... (you'd use output from above)
from datetime import timedelta
run_at = now + timedelta(hours=3)
delay = (run_at - now).total_seconds()

You can then use delay to pass into a threading.Timer instance, eg:

threading.Timer(delay, self.update).start()

Start a Function at a specific time range

You cannot directly set until condition as the day of week and time in schedule API but can set an explicit datetime, time, or a timedelta object as an argument in the until() function. See apidocs.

Also, you cannot schedule a job with a day of week and every x minutes.
Something like schedule.every(5).minutes.sunday.at("23:00") is not allowed.

Try something like this to first find the date of next Sunday then calculate the following Friday date from it. Now you have the starting and ending times.

Next, you can call sleep until the start time then you can start to schedule the job.

import time
from datetime import datetime, timedelta
import schedule

def script_sample():
now = datetime.now()
print(now)

now = datetime.now()
# find date of next sunday
d = now
# weekday(): Monday is 0 and Sunday is 6
while d.weekday() != 6:
d += timedelta(days=1)
d = d.replace(hour=23, minute=00, second=0, microsecond=0)
print("now=", now)
print("next sunday", d) # start date
wait_time = d - now

wait_time_secs = wait_time.total_seconds()
if wait_time_secs > 0:
print("wait time is ", wait_time)
print("waiting to start...")
time.sleep(wait_time_secs)
else:
print("no need to wait. let's get started')

This part of the code will be complete when it is Sunday at 23:00 or just late on Sunday if it was started on Sunday after 23:00.

Part 2 of the code below is to determine the until condition and schedule the job to run. Next find the date of next Friday which is the until condition in the schedule. Finally schedule the job to run every 5 minutes until Friday at 23:00.

# next find date of next Friday (friday=5)
while d.weekday() != 5:
d += timedelta(days=1)
endtime = d.replace(hour=23, minute=00, second=0, microsecond=0)
print("end time", endtime)

# now schedule a job every 5 mins until the end time
schedule.every(5).minutes.until(endtime).do(script_sample)

while True:
schedule.run_pending()

How to run a function at specific time & date?

It's not advised to use setInterval because it has non-deterministic behaviour - events can be missed, or fire all at once. Time will fall out of sync, too.

The code below instead uses setTimeout with a one minute period, where each minute the timer is resynchronised so as to fall as closely to the hh:mm:00.000s point as possible.

function surprise(cb) {
(function loop() {
var now = new Date();
if (now.getDate() === 12 && now.getHours() === 12 && now.getMinutes() === 0) {
cb();
}
now = new Date(); // allow for time passing
var delay = 60000 - (now % 60000); // exact ms to next minute interval
setTimeout(loop, delay);
})();
}

In JavaScript, how can I have a function run at a specific time?

JavaScript is not the tool for this. If you want something to run at a specific time every day, you're almost certainly looking for something that runs locally, like python or applescript.


However, let's consider for a moment that JavaScript is your only option. There are a few ways that you could do this, but I'll give you the simplest.

First, you'll have to to create a new Date() and set a checking interval to see whether the hour is 8 (for 8 AM).

This will check every minute (60000 milliseconds) to see if it is eight o'clock:

window.setInterval(function(){ // Set interval for checking
var date = new Date(); // Create a Date object to find out what time it is
if(date.getHours() === 8 && date.getMinutes() === 0){ // Check the time
// Do stuff
}
}, 60000); // Repeat every 60000 milliseconds (1 minute)

It won't execute at exactly 8 o'clock (unless you start running this right on the minute) because it is checking once per minute. You could decrease the interval as much as you'd like to increase the accuracy of the check, but this is overkill as it is: it will check every minute of every hour of every day to see whether it is 8 o'clock.

The intensity of the checking is due to the nature of JavaScript: there are much better languages and frameworks for this sort of thing. Because JavaScript runs on webpages as you load them, it is not meant to handle long-lasting, extended tasks.

Also realize that this requires the webpage that it is being executed on to be open. That is, you can't have a scheduled action occur every day at 8 AM if the page isn't open doing the counting and checking every minute.

You say that you are already refreshing the page every five seconds: if that's true, you don't need the timer at all. Just check every time you refresh the page:

var date = new Date(); // Create Date object for a reference point
if(date.getHours() === 8 && date.getMinutes() === 0 && date.getSeconds() < 10){ // Check the time like above
// Do stuff
}

With this, you also have to check the seconds because you're refreshing every five seconds, so you would get duplicate tasks.


With that said, you might want to do something like this or write an Automator workflow for scheduled tasks on OS X.

If you need something more platform-agnostic, I'd seriously consider taking a look at Python or Bash.


As an update, JavaScript for Automation was introduced with OS X Yosemite, and it seems to offer a viable way to use JavaScript for this sort of thing (although obviously you're not using it in the same context; Apple is just giving you an interface for using another scripting language locally).

If you're on OS X and really want to use JavaScript, I think this is the way to go.

The release notes linked to above appear to be the only existing documentation as of this writing (which is ~2 months after Yosemite's release to the public), but they're worth a read. You can also take a look at the javascript-automation tag for some examples.

I've also found the JXA Cookbook extremely helpful.

You might have to tweak this approach a bit to adjust for your particular situation, but I'll give a general overview.

  1. Create a blank Application in Automator.

    • Open Automator.app (it should be in your Applications directory) and create a new document.
    • From the dialog, choose "Application."
      Automator new document dialog
  2. Add a JavaScript action.

    • The next step is to actually add the JavaScript that will be executed. To do that, start by adding a "Run JavaScript" action from the sidebar to the workflow.
      Drag the JS file into the workflow
  3. Write the JavaScript.

    • This is where you'll have to know what you want to do before proceeding. From what you've provided, I'm assuming you want to execute window.print() on a page loaded in Safari. You can do that (or, more generally, execute arbitrary JS in a Safari tab) with this:

      var safari = Application('Safari');
      safari.doJavaScript('window.print();', { in: safari.windows[0].currentTab });
    • You might have to adjust which of the windows you're accessing depending on your setup.
  4. Save the Application.

    • Save (File -> Save or +S) the file as an Application in a location you can find (or iCloud).
  5. Schedule it to run.

    • Open Calendar (or iCal).
    • Create a new event and give it an identifiable name; then, set the time to your desired run time (8:00 AM in this case).
    • Set the event to repeat daily (or weekly, monthly, etc. – however often you'd like it to run).
    • Set the alert (or alarm, depending on your version) to custom.
    • Choose "Open file" and select the Application file that you saved.
    • Choose "At time of event" for the alert timing option.
      GIF instructions for scheduling the event

That's it! The JavaScript code that you wrote in the Application file will run every time that event is set to run. You should be able to go back to your file in Automator and modify the code if needed.

How to start/stop a function at specific time of the day?

If I understand the question correctly, you could just check the time using an if statement:

# import datetime module
from datetime import datetime as dt

# set to time bounds:
lower_bound = dt.time(13, 50)
upper_bound = dt.time(14, 20)

Then just check the time whenever the function runs:

now = dt.now().time()
if lower_bound < now < upper_bound:
pass
if not (lower_boun < now < upper_bond):
Show() #that returns something.

...or just put the if statements into the function itself

Check out this question on now() and this question on comparing time

Answer improved by helpful comments of chepner and 0x5423

python how to run a function everyday at specific time, but can also be terminated

Try this example

from datetime import datetime

from apscheduler.schedulers.background import BackgroundScheduler

def job_function():
print("Hello World")

sched = BackgroundScheduler()

# Schedule job_function to be called every 1 second
# FIXME: Do not forget to change end_date to actual date
sched.add_job(job_function, 'interval', seconds=1, end_date="2017-09-08 12:22:20")

sched.start()

Update #1

from apscheduler.schedulers.background import BackgroundScheduler

def job_function():
print("Hello World")

# Here, you can generate your needed days
dates = ["2017-09-08 13:30:20", "2017-09-08 13:31:20", "2017-09-08 13:32:20"]
sched = BackgroundScheduler()

for date in dates:
sched.add_job(job_function, "date", next_run_time=date)

sched.start()

Call a javascript function at a specific time of day

You'll need setTimeout to set a timer and Date to calculate how long the timer needs to go until it triggers.

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){alert("It's 10am!")}, millisTill10);

Javascript: Call a function after specific time period

You can use JavaScript Timing Events to call function after certain interval of time:

This shows the alert box every 3 seconds:

setInterval(function(){alert("Hello")},3000);

You can use two method of time event in javascript.i.e.

  1. setInterval(): executes a function, over and over again, at
    specified time intervals
  2. setTimeout() : executes a function, once, after waiting a
    specified number of milliseconds


Related Topics



Leave a reply



Submit