Forums

A way to kill running tasks using API?

Hello, I am currently running a discord bot using pythonanywhere to hose it. Since I am using async function, the script (bot) keeps on running forever. I was wondering if there is a way to kill this running task using API. My thinking is that I can create a script that I can schedule which will kill the discord bot script. I want to do this because I notice that if I let the discord bot script run, eventually I will end up with multiple running tasks.

Is it a Scheduled Task or Always-on Task?

Its a scheduled task. I tried to look at killing it via the os module, but that doesn't work.

We do not have an API to kill a running scheduled task process. Is there a reason you're not using an always on task for this? It's a much better fit to what you're trying to accomplish.

Yes, I am currently using the bot from set timings (9am IST to 330pm IST), so I was thinking that instead of just keeping it on, I might as well turn it off.

I'd say that the best way to do that would be to have an always-on task that actually runs the bot, and then to have two scheduled tasks that use the API -- one at 9am IST that sets the always-on task to enabled, and one at 3:30pm IST that disables it.

Oh, I see. This method is also very good. Thank you :)

Glad it works for you!

Hey, so I looked at the API docs and tried the following:

postrequest = requests.post( url='https://www.pythonanywhere.com/api/v0/user/{username}/always_on/'.format( username=username), headers={'Authorization': 'Token {token}'.format(token=token)}, command='python3.8 /home/soulreaper/bot.py', enabled=True )

but I get the following error: TypeError: request() got an unexpected keyword argument 'command'

my understanding is that it shouldn't give that error as POST function has **kwargs. What am I doing wrong?

Instead of command='python3.8 /home/soulreaper/bot.py', enabled=True run your requests.post with json={"command": "python3.8 /home/soulreaper/bot.py", "enabled": True}

Thank you! Now it works, and I see what was wrong.

Glad to hear that you made it work!

Hey, just another question. So what is the difference between the PUT and PATCH method (in always on task)? I see them having the same definitions.

We treat them as the same. Technically there should be a subtle difference (PUT replaces the existing task with a new one with some differences, while PATCH updates the existing one in-place) but for always-on tasks we felt there was no useful difference, so they both update in-place.

Gotcha, so can I use, for example, PATCH to Enable: True and Enable: False. Will that be enough to start and pause the always-on Task?

Yes, using PATCH with "enabled": True or "enabled": False will toggle pause for an existing task.

Got it, thanks!

No problem.