1

this is the code:

import datetime
import schedule
import time

local = datetime.datetime.now().time().replace(microsecond=0)
hour = str(local)

def job():
    if hour.startswith('16'):
        print("Hi! It's ", local)
    else:
        print("nope!")

schedule.every(10).minutes.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

I'm trying to repeat job (if current hour starts with 16 then say hi it's local , if it doesn't say nope) every 10 minutes, but it gives the same response every time, example, started the code at 16:40, gives right answer (hi it's local) but after 17:00 it still gives the same answer with the old time instead of just saying nope (or the right time), I'm not sure if the schedule code is right, need some help, ty!

Yukon
  • 57
  • 1
  • 9
  • 2
    `hour` is a global string value, set just once. It will not change with each call to `job()`. – Martijn Pieters Aug 06 '19 at 16:40
  • thanks for the answer, how would I execute what I'm trying to do, is there another method? – Yukon Aug 06 '19 at 16:42
  • 1
    You're never updating `local` or `hour`. You should place them both inside `job` so they update every time you call `job`. – SyntaxVoid Aug 06 '19 at 16:42
  • 1
    If you want to check the **current** time, then call `datetime.datetime.now()` inside your `job` function. Note that `time` objects have an `hour` attribute, that's a much better value to test with. – Martijn Pieters Aug 06 '19 at 16:42

1 Answers1

0

This should work, notice the reading of current time inside the job function:

from datetime import datetime
import schedule
import time

def job():
    local = datetime.now().time().replace(microsecond=0)
    if local.hour == 16:
        print("Hi! It's ", local)
    else:
        print("nope!")

schedule.every(10).minutes.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
Sagar Gupta
  • 1,352
  • 1
  • 12
  • 26