Home > Software engineering >  How to make auto-run python file when time is 06:00 P.M
How to make auto-run python file when time is 06:00 P.M

Time:12-07

I have telegram bot which is made by python. The file must run at 06:00 P.M everyday. My PC is Windows 10. How can I achieve this , please guide me.

CodePudding user response:

You can use Windows scheduled tasks:

  1. Save your python file. For example: my_python.py

  2. Create a bat file that runs my_python.py. Assuming Python is installed in the path below:

    "C:\Users\MyUser\AppData\Local\Programs\Python\Python37-32\python.exe"

And my_python is saved in:

"C:\Users\MyUser\Desktop\my_python.py"

Create new text file and save it as run_my_python.bat with the following content:

"C:\Users\MyUser\AppData\Local\Programs\Python\Python37-32\python.exe" "C:\Users\MyUser\Desktop\my_python.py"
  1. Create a scheduled task to run run_my_python.bat. Go to Windows Task Scheduler, set your trigger, and choose "Start a program" action. Select run_my_python and save the scheduled task.

CodePudding user response:

If you are using python-telegram-bot you should take a look at JobQueue. It has a run_daily which does what you want:

run_daily(callback, time, days=(0, 1, 2, 3, 4, 5, 6), context=None, name=None)

Here is an example with it:

    def daily_function(context: telegram.ext.CallbackContext):
      bot.send_message(chat_id=id, text='Daily message')

    def call_daily_message(update,context):
       context.job_queue.run_daily(daily_function, context=update.message.chat_id,days=(0, 1, 2, 3, 4, 5, 6),time = time(hour = 18, minute = 0, second = 0))

This example executes the function daily_function everyday at 18:00.

CodePudding user response:

  1. Find out your python exe path, e.g., C:\python-path\python.exe
  2. Save your python script somewhere and note the path
  3. Then, open the Task Scheduler
  4. Go to Actions > Create Task
  5. Give it a name and then Go to Actions > New
  6. Ensure the action is 'Start a program'
  7. In the "Program/script" you will add the path of the python exe (C:\python-path\python.exe).
  8. In the "Add arguments (optional)” box, you will add the name of your python file (e.g., myScript.py).
  9. In the "Start in (optional)" box, you will add the location of your python file (the whole path of the file, C:\path-to-the-python-script).

I hope this to fulfill your requirements.

BR

  • Related