SoFunction
Updated on 2025-05-20

How to start and close some python scripts regularly

Timed self-start and self-close some python scripts

It's a Windows system, it would be great if it was Linux.

This is the idea

First, start the script or a software at 6 o'clock in the morning, then record the corresponding pid, and wait until 18 o'clock in the evening, automatically kill the corresponding process according to the pid.

Use apscheduler to turn on and off regularly, the sample code is as follows:

from   import BlockingScheduler 

def start_scripts():
	pass
	
def kill_processes():
	pass
	
if __name__ == "__main__":
    
	scheduler = BlockingScheduler()
	# Add timed tasks (crontab format)	scheduler.add_job(start_scripts, 'cron', hour=6, minute=0   # start up	scheduler.add_job(kill_processes, 'cron', hour=18, minute=0  # Termination	print("The monitoring program has been started")
	try:
		() 
	except (KeyboardInterrupt, SystemExit):
		pass 
    

In order to ensure that the corresponding real pid is obtained when starting the program, use the subprocess dependency library

import subprocess 


try:
	(
		["python", script], 
		cwd="d:/file/script/",
		creationflags=subprocess.CREATE_NEW_CONSOLE)
except Exception as e:
	print(f"Startup failed:{str(e)}")
	
try:
	proc = (
		["d:/file/soft/"], 
		cwd="d:/file/soft/")
	pid = str()
	with open("", 'a') as f:         
        (f"-pid={pid}\n")
except Exception as e:
	print(f"Startup failed:{str(e)}")

	

The startup script window does not get the pid here because once the new window is opened, the acquisition is invalid. The AI ​​says:

  • In Windows 7 and earlier, new consoles are generatedHost process
  • The returned PID points to the console host process, not the actual target process
  • New architecture differences: Windows 8+ adoptsconhostNew architecture separate from terminals, while Win7 uses traditional mode

In short, to avoid this

I read the pid in the started python script and use the psutil library as follows:

import psutil 

current_process = ()
pid = str(current_process.pid)
print(f"Current processID: {pid}")
with open("", 'a') as f:         
    (f"script-1-pid={pid}\n") 

This will avoid the problem of returning pid exceptions. In the later stage, you can wait until 18 o'clock in the evening to read the pid file and kill it in order.

Of course, if you want to execute it every once in a while, you can do this:

def print_fun():
	print("Execution time:", ())

scheduler.add_job(print_fun, 'interval', seconds=10)

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.