Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a python script in the future

Tags:

I have got a python script which needs to be run on the user inputs. I will get the date and time from user and the script will run at that date.

import time
from datetime import datetime

today = datetime.today() 
enter_date = raw_input("Please enter a date:(2017-11-28): ")
enter_time = raw_input("What time do you want to start the script? ")

difference = enter_date - today

time.sleep(difference)

After this point main() function will run.

I could not make it run. Is there any better way to achieve this task ? Thanks

like image 367
pylearner Avatar asked Nov 28 '17 10:11

pylearner


2 Answers

import time
from datetime import datetime

date_format = "%d/%m/%y %H:%M"
today = datetime.today() 

print("Please enter date in format dd/mm/yy HH:MM")

enter_date = datetime.strptime(
    raw_input("> "),
    date_format)

difference = enter_date - today

print(difference)


#time.sleep(difference.total_seconds())

Uncomment sleep if you want. However this is a bad solution. You should OS specific features to do that. For example you could add line with you script to cronjob file on linux etc. https://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/

like image 141
Prime Reaper Avatar answered Sep 23 '22 09:09

Prime Reaper


Asumming you can execute cron jobs, a nice solution would be to split your script in two parts, one to request when the script will be executed and the other one the actual script.

Your first script will create a cron job to schedule the execution of the script, for that you can use the python-crontab package:

pip install python-crontab

To create the cron job:

from datetime import datetime
from crontab import CronTab

run_date_input = raw_input("Please enter a date (e.g. 2017-11-28): ")
run_time_input = raw_input("What time do you want to start the script (e.g. 14:30:12)? ")

run_date = datetime.strptime(run_date_input, "%y-%m-%d")
run_time = datetime.strptime(run_time_input, "%H:%M:%S")

#Access the crontab for the current user (on unix systems)
user_cron = CronTab(user='your username')

#Access the crontab (on windows sytems)
user_cron = CronTab(tabfile='c:/path_to_your_tab_file/filename.tab')

#Create a new job
job = user_cron.new(command='python /home/your_second_script.py')
job.setall(datetime(run_date.year, run_date.month, run_date.day, run_time.hour, run_time.minute, run_time.second))

If you use windows you need to install cron for windows using something like cygwin or the new Linux subsystem for Windows 10.

like image 37
Isma Avatar answered Sep 20 '22 09:09

Isma