How to Stop Django or Flask Server without Ctrl + C

Ctrl + C is an awesome and common way to stop most process especially when being run from the terminal. In this tutorial we will explore how to stop a Django application or Flask application without using Ctrl + C.

This idea is useful when you are working within a script or a CI/CD pipeline and you want to stop your running application after sometime. It can also be used for automating and scheduling when to stop an application.

Let us see how to do so.

The basic idea behind these approach is that every application be it flask or django is being treated as a process. Hence if you know the process ID (PID) you can kill that process and shutdown the application. This is what Ctrl + C actually does.

So the steps are

  • Identify the Process and the Process ID of the running application or server
  • Kill the process
  • Automate by scheduling when to kill the process using at.

Identifying the Process and Process ID (PID)

There are several ways to identify a process on unix based systems.You can use ps and grep or pgrep etc.

ps aux | grep "python3 runserver"

The aux argument keeps the ps command from also appearing in the list of all the process being displaced.

You can also use pgrep -f to directly get the process id of the process.

Kill the Process

To kill a process you can use the kill command and pass in the process via xargs

pgrep -f  "python3 runserver" | xargs kill -9 

Alternatively you can also use pkill directly.

The pkill is for process kill. This is what we will use. It also accepts a keyword argument -f for keyword to use to fetch a process.

pkill -9 -f "python3 runserver" 

Automating or Scheduling when to kill the process.

Using the at command we can schedule when to kill the process. In case you don’t have at installed you can use

sudo apt-get install at

With the at you can schedule the precise minute,hour,days to perform a task.

You can pipe a command to the at command and it will execute at the specified time. We use the echo to echo the command and then pipe it to at. So in the command below we are scheduling the task to run 1 minute from now (at now + 1 minute)

echo 'pkill -9 -f "python3 runserver"' | at now + 1 minute

To conclude we have seen how to stop or shutdown a django application or flask application without using Ctrl + C.

You can also check out the video tutorial below.

Thanks For Your Attention
Jesus Saves

By Jesse E.Agbe(JCharis)

Leave a Comment

Your email address will not be published. Required fields are marked *