I want to show off some of my work, but i don't want it to be kept forever.
I've tried this trial period that checks on launch if date has past.
from datetime import datetime, timedelta
def check_trial():
trial_start = "2019-09-03"
trial_end = datetime.strptime(trial_start, '%Y-%m-%d') + timedelta(days=5)
today = datetime.now()
if today > trial_end:
print("Trial Expired")
os._exit()
def main():
print("running")
check_trial()
main()
Im scared if they just change their computer date then this wont run. What should be done to protect against that?
Not sure if this completes your requirement but here is an alternate method using signal module in python. Let us suppose that run() function runs your application and you want it to run for 10 mins.
import signal
signal.alarm(600)
run()
signal.alarm(0)
This will simply run your run() function till 600 seconds and if the function doesn't stop execution it will forcefully break the execution of the function.
Related
I am using below code to excute a python script every 5 minutes but when it executes next time its not excecuting at excact time as before.
example if i am executing it at exact 9:00:00 AM, next time it executes at 9:05:25 AM and next time 9:10:45 AM. as i run the python script every 5 minutes for long time its not able to record at exact time.
import schedule
import time
from datetime import datetime
# Functions setup
def geeks():
print("Shaurya says Geeksforgeeks")
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
# Task scheduling
# After every 10mins geeks() is called.
schedule.every(2).minutes.do(geeks)
# Loop so that the scheduling task
# keeps on running all time.
while True:
# Checks whether a scheduled task
# is pending to run or not
schedule.run_pending()
time.sleep(1)
Is there any easy fix for this so that the script runs exactly at 5 minutes next time.
please don't suggest me to use crontab as I have tried crontabs ut not working for me.
I am using python script in different os
your geeks function will cost time to execute,and schedule job start calculate 5min after geeks done,that's why long time its not able to record at exact time.
if you want your function run at exact time,you can trying this:
# After every 10mins geeks() is called.
#schedule.every(2).minutes.do(geeks)
for _ in range(0,60,5):
schedule.every().hour.at(":"+str(_).zfill(2)).do(geeks)
# Loop so that the scheduling task
It's because schedule does not account for the time it takes for the job function to execute. Use ischedule instead. The following would work for your task.
import ischedule
ischedule.schedule(geeks, interval=2*60)
ischedule.run_loop()
I'm using appjar to create a python app that includes the feature to set an alarm to go off at a certain time/date. However, based on my simple implementation, when calling the alarm function in the code the application will just infinitely wait for the alarm to go off before allowing anything else to happen.
I want to be able to navigate around the app without it having to wait on the alarm. What is the best way to go about doing this?
Here is my alarm code:
def setAlarm(year, month, day, hour, minute, second):
now = datetime.datetime.now()
date = datetime.date(year, month, day)
time = datetime.time(hour, minute, second)
alarmTime = datetime.datetime(year, month, day, hour, minute, second)
while now < alarmTime:
print("not yet")
mixer.music.load('Alarm.wav')
mixer.music.play(-1)
sound = True
while(sound):
print("Alarm")
Check out Python Timers. If this doesn't work, your solution will involve some kind of multi-threading or multiprocessing such that you can have two paths of execution running at the same time.
You should be able to set a timer for a short amount of time. When the timer goes off, have the code that it runs when it does check for the condition you're waiting for. If that condition still isn't met, have that code fire off a new timer to wait some more. When you create and start a timer, control returns immediately to your code, so you can go on and do other things.
I have gone through the same problem then I solved it in my way.
import time
from playsound import playsound
import threading
from datetime import datetime
import playsound
#taking input from user
alarmH = 3
alarmM = 10
amPm = 'am'
print("Weating for the alarm",alarmH,alarmM,amPm)
if (amPm == "pm"):
alarmH = alarmH + 12
#Current Date Time
now = datetime.now()
#desired alarm time
later = datetime(2020,5,1,alarmH,alarmM,0)
#calculating the difference between two time
difference = (later - now)
#difference in seconds
total_sec=difference.total_seconds()
def alarm_func():
playsound.playsound('audio/alarm.mp3', True)
timer = threading.Timer(total_sec, alarm_func)
timer.start()
I'm new to explore how to do this in python. What I want to do is run a function every business day at a specific time, e.g., say at 14:55, just 5 minutes before the stock market closes in China. This function will pull some data from a stock market data feeding API and do some simple calculations to generate a signal(-1 means to short, +1 means to long, 0 means don't do anything). I'm not sending the signal yet to make a trade now. I'm just saving the signals everyday to a file locally. Thus, I might be able to collect the signals for 2 weeks or any time I feel like to stop this scheduler.
I notice that APScheduler module being suggested quite often. But I tried it, didn't find a way to make the scheduler stop running 2 weeks after. I only find ways to set up a scheduler to run, maybe every 10 minutes, but it will just keep running a specified function every 10 minutes and can't be stopped programmally, but only through pressing Ctrl+C? For example, I want to run a function every 10 minutes for 6 times, in APScheduler, I didn't see anyway to specify the '6 times' argument. Or I want to run a function every 10 minutes until 1 hour later. I didn't see the '1 hour later' or 'at 16:30' argument either. How to do it?
Currently, I'm doing it this way:
def test_timer():
'''
Uses datetime module.
'''
running = 1
stop_time = datetime.now() + timedelta(seconds=60)
while running:
print('I\'m working...')
time.sleep(5)
running = datetime.now() < stop_time
print('Goodbye!')
Edited: I'm using python 3.6 in Windows 10.
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()
Looks like a problem for crontab in Linux or Task Scheduler in Windows.
How do I have a part of python script(only a method, the whole script runs in 24/7) run everyday at a set-time, exactly at every 20th minutes? Like 12:20, 12:40, 13:00 in every hour.
I can not use cron, I tried periodic execution but that is not as accurate as I would... It depends from the script starting time.
Module schedule may be useful for this. See answer to
How do I get a Cron like scheduler in Python? for details.
You can either put calling this method in a loop, which would sleep for some time
from time import sleep
while True:
sleep(1200)
my_function()
and be triggered once in a while, you could use datetime to compare current timestamp and set next executions.
import datetime
function_executed = False
trigger_time = datetime.datetime.now()
def set_trigger_time():
global function executed = False
return datetime.datetime.now() + datetime.timedelta(minutes=20)
while True:
if function_executed:
triggertime = set_trigger_time()
if datetime.datetime.now() == triggertime:
function_executed = True
my_function()
I think however making a system call the script would be a nicer solution.
Use for example redis for that and rq-scheduler package. You can schedule tasks with specific time. So you can run first script, save to the variable starting time, calculate starting time + 20 mins and if your current script will end, at the end you will push another, the same task with proper time.
I have written a scraper that does html scraping and then use API to get some data, since its a very lengthy code I haven't put it here. I have implemented random sleep method and using it within my code to monitor throttle. But I want to make sure I don't over run this code, so my idea is to run for an 3-4 hours then taker breather and then run again. I haven't done anything like this in python I was trying to search but not really sure where to start from, it would be great if I get some guidance on this. If python has a specific module link to that would be a great help.
Also is this relevant? I don't I need this level of complication?
Suggestions for a Cron like scheduler in Python?
I have functions for every single scraping task, and I have main method calling all those functions.
You can use a threading.Timer object to schedule an interrupt signal to the main thread after the time is exceeded:
import thread, threading
def longjob():
try:
# do your job
while True:
print '*',
except KeyboardInterrupt:
# do your cleanup
print 'ok, giving up'
def terminate():
print 'sorry, pal'
thread.interrupt_main()
time_limit = 5 # terminate in 5 seconds
threading.Timer(time_limit, terminate).start()
longjob()
Put this in your crontab and run every time_limit + 2 minutes.
You could just note the time you have started and each time you want to run something make sure you haven't exceeded the given maximum. Something like this should get you started:
from datetime import datetime
MAX_SECONDS = 3600
# note the time you have started
start = datetime.now()
while True:
current = datetime.now()
diff = current-start
if diff.seconds >= MAX_SECONDS:
# break the loop after MAX_SECONDS
break
# MAX_SECONDS not exceeded, run more tasks
scrape_some_more()
Here's the link to the datetime module documentation.