Alexander Caskie
Alexander Caskie

Reputation: 357

Have function run at a particular time using python

I am trying to have a function run once at a particular time. I have used My code is the following:

import pytz
import datetime
import time

def test_1():

    print("Working_1")


def test_2():

    print("Working_2")


while True:

    current_time = datetime.datetime.now(pytz.timezone('GMT')).strftime('%Y-%m-%dT%H:%M:%SZ')

    if current_time == '2019-03-18T19:00:36Z':

        test_1()

        current_time = datetime.datetime.now(pytz.timezone('GMT')).strftime('%Y-%m-%dT%H:%M:%SZ')


        if current_time > '2019-03-18T19:00:36Z':

            break

        if current_time == '2019-03-18T19:00:36Z':

            test_2()


            current_time = datetime.datetime.now(pytz.timezone('GMT')).strftime('%Y-%m-%dT%H:%M:%SZ')


            if current_time > '2019-03-18T19:00:36Z':

                break

When I run my code it runs the first function followed by the second one until the end condition.

I want the function to run at the specified times in the if statement.

I think the problem is occurring about how loops are nested. I have tried multiple configurations of the if statement and break condition but just cannot get it.

Any help would be much appreciated, cheers. Sandy

Upvotes: 0

Views: 107

Answers (2)

B. Shefter
B. Shefter

Reputation: 897

Taking my best guess at what you want: You want both functions to run, in order, at a particular time, yes? Something much simpler should work, like this:

current_time = datetime.datetime.now(pytz.timezone('GMT')).strftime('%Y-%m-%dT%H:%M:%SZ')
while current_time < '2019-03-18T19:00:36Z':
    current_time = datetime.datetime.now(pytz.timezone('GMT')).strftime('%Y-%m-%dT%H:%M:%SZ')
test_1()
test_2()

This will run both functions as soon as the clock hits or passes your target time.

EDIT: If you want them to run at two different times:

current_time = datetime.datetime.now(pytz.timezone('GMT')).strftime('%Y-%m-%dT%H:%M:%SZ')
while current_time < '<first_time>':
    current_time = datetime.datetime.now(pytz.timezone('GMT')).strftime('%Y-%m-%dT%H:%M:%SZ')
test_1()
while current_time < '<second_time>':
    current_time = datetime.datetime.now(pytz.timezone('GMT')).strftime('%Y-%m-%dT%H:%M:%SZ')
test_2()

(where <first_time> is first chronologically)

Upvotes: 1

MonoHearted
MonoHearted

Reputation: 83

I believe your code here doesn't work because it would require the time to be EXACTLY the timestamp given, and when accounting for run-time, even if minimal, this is quite unrealistic. A possible solution is to give a "time cushion", i.e a window around the execution time rather than an exact match for the if statement; however this is still quite unreliable.

If you don't mind using an external module, I would recommend you take a look at sched or APScheduler. I've personally used the latter, and it works great.

Upvotes: 2

Related Questions