Cron jobs in php

How To Execute and List Cron Jobs for a Linux System via PHP

Ransomware recovery test drive: This technical workshop is designed to take you behind the scenes and shows you how to adopt strategies to automate recovery, ensuring you’re ready to become a recovery hero. REQUEST YOUR LAB

Working with cron jobs manually is most commonplace with low volumes of cron jobs. But what if you’re working with high volumes of cron jobs? PHP is the answer! Why PHP? Simply because it can automate the tasks needed to add, remove and list cron jobs.

Not a reader? Watch this related video tutorial!

In this tutorial, you will learn how PHP can save time by automating adding, removing, and listing cron jobs for a Linux system.

Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

  • Crontab – Crontab is typically installed on Linux operating systems by default.
  • Most Linux distributions utilize the same cron system. The examples are shown here on a macOS using a BSD-based underlying system.

Creating the Crontab File

Before you can manage cron jobs, you first need a file to store those cron jobs. All cron jobs are stored in one system-wide crontab file.

Open your terminal and run the command below to change directory to /usr/local and create subdirectories ( jobs and scripts ). You can name these directories differently as you prefer. These directories will store your cron job files and scripts later.

cd /usr/local && sudo mkdir jobs scripts

Now run the command below to create the crontab file ( crontab -e ). The crontab file is created automatically inside your ~/tmp directory the first time you invoke a crontab command.

# Sets default text editor to nano export EDITOR='nano' # Initializes the crontab file and opens it in nano crontab -e

Adding Single Cron Jobs

Now that you’ve created the crontab file, you can start managing your cron jobs. But you first need to focus on adding them via PHP. How? You’ll create and execute a PHP script to add cron jobs.

Cron jobs are scheduled with five parameters, as shown below. Each parameter has a default value of *, which indicates that no value was specified for that parameter, whether for hourly, daily, weekly, or monthly cron jobs.

If you need a refresher on the cron job syntax with examples, take a look at crontab’s website.

1. Create a file in your text editor, copy/paste the code below and save it in the /usr/local/jobs directory. For this example, the file is named newjob.py, but you can name it differently. The code below prints a text ( Executed! ) when executed.

Читайте также:  Java run jar without manifest

2. Next, create a PHP script file, then copy/paste the code below to that PHP file, and save it in the /usr/local/scripts. For this tutorial, the script is named add.php.

Throughout the tutorial, bear in mind to save the script files in the /usr/local/scripts directory and the cron job files in the /usr/local/jobs directory.

The code below adds the newjob.py file as cron job in the crontab file.

The shell_exec operation stores the list of cron jobs to a string in memory before adding a new one, so you won’t lose any of the existing cron jobs.

Does shell_exec not work? You may have this function disabled in your php.ini file. Look for the disable_functions configuration in your php.ini and remove shell_exec from the list. Keep in mind that this can be abused, so be careful with this function!

3. Run the command below to execute the add.php script from the /usr/local/scripts directory. php add.php

Ensure you’re in the /usr/local/scripts directory when executing scripts throughout the tutorial.

4. Finally, run the below crontab -l command to check if the new cron job exists.

Listing Cron Jobs

Listing Cron Jobs

Perhaps you want to keep track of the cron jobs you’ve added, so you can either update or remove them. If so, your first step is to list the existing cron jobs. Listing cron jobs come in handy to keep track of the cron jobs you have.

Create a new PHP script, give it a unique name, and paste the code below to the script file. For this example, the script is named list.php.

The below code’s shell_exec operation gathers and displays ( echo() ) all cron jobs ( crontab -l ) from the crontab file.

Now, run the command below to execute the list.php script.

Executing PHP script to List Cron Jobs

Listing an Array of Cron Jobs

Perhaps you want to print the list of cron jobs in an array instead of a plain list. If so, you’ll need the explode() functions. These functions let you store cron jobs inside the crontab file as an element inside an array.

Replace the content of the list.php file with the code below. Executing the code below lists an array of cron jobs, and also prints the string length of the cron job.

Now run the command below to execute the list.php script.

Читайте также:  Python импортировать все модули

As you see below, the code outputs the list of cron jobs in an array, while also showing the string length.

Listing Cron Jobs in Array

Removing Cron Jobs

Now that you have the list of existing cron jobs, you get to decide what you want to do with each cron job. Perhaps you have cron jobs that you want to remove. If so, you’ll specify the cron job to remove in a string variable.

1. Create a new PHP script called remove.php for this example, then add the code below to the script. You can name the script file differently as you prefer.

The below code removes a specific cron job from the crontab file.

2. Run the following command to execute the remove.php script.

3. Finally, run the crontab -l command to see if you’ve removed the newjob.php cron job. crontab -l

Verifying newjob.php is Removed

Adding and Removing Multiple Cron Jobs

From adding a single cron job, you can also add multiple cron jobs, perhaps when you have daily tasks you want to automate. How? By adding a for loop in your script.

Adding and removing multiple cron jobs share a similar approach, but the script to remove multiple cron jobs has more use of variables, as demonstrated below.

1. Replace the content of your add.php file with the code below. Executing the code below adds multiple cron jobs to the crontab file by paddling through an array.

2. Next, rerun the command below to execute the add.php script. php add.php

3. Run the below crontab -l command to verify if the cron jobs that you added in the crontab file exist. crontab -l

Verifying Added Multiple Cron Jobs Exist

4. Now, replace the content of your remove.php file with the code below, which removes multiple cron jobs that you defined. Similar to adding multiple cron jobs, the same approach applies in removing multiple cron jobs, but with additional variables.

5. Run the following command to execute the remove.php script.

6. Finally, run the crontab -l command to verify you’ve removed the cron jobs.

If you’ve successfully removed the cron jobs, you won’t get an output like the one below.

Cron Jobs are Removed

Creating Functions to Manage Cron Jobs

So far you’ve seen how can add, remove and list cron jobs in separate scripts. But to effectively manage cron jobs, you can create functions in a single script instead of running three separate scripts.

Create a new script file and paste the code below. Give the script any name you prefer, but for this example, the script is named multi.php.

The code below adds, removes, and lists cron jobs with three separate functions that you can call at the bottom of the script.

 # Removes a crob job from the crontab file function remove_job() < $jobs = shell_exec("crontab -l"); $to_remove = "* * * * * php /usr/local/scripts/oldjob.php"; $removed = str_replace($to_remove,"",$jobs); shell_exec("echo '$removed' | sort | uniq | crontab"); ># Lists existing cron jobs function list_jobs() < echo(shell_exec("crontab -l")); >// CALL THE FUNCTIONS HERE // Call the functions that adds and removes cron jobs but provide no output add_job() remove_job() // Calls the function that outputs a list all exiting cron jobs list_jobs() ?> 

Now, run the command below to execute the multi.php script.

Читайте также:  Задачи с циклами javascript

Below, you can see the output of list_jobs() function called in the multi.php script.

Executing the multi.php Script

Preventing Memory Overload

You’ve seen PHP’s capabilities in managing cron jobs, but having too many cron jobs consumes memory. How to avoid memory overload? Set a count limit to how many cron jobs you can add to the crontab file.

1. Add the following function to the multi.php script. The function below counts all cron jobs by counting all lines inside the crontab file and prints a message to inform you of the current cron job count.

2. Next, call the count_jobs() function at the end of the script, as you did in the “Creating Functions to Manage Cron Jobs” section.

3. Run the command below to execute the multi.php script.

As you can see below, there’s a message that tells you the current cron jobs count.

Executing the multi.php which Outputs the Current Cron Jobs Count

But perhaps you want to automatically terminate the script if there are too many cron jobs running simultaneously. If so, adding an if condition will do the trick.

4. Replace the count_jobs() function in the multi.php file with the one below.

The function below reads the number of lines inside the crontab file, and based on that number, decides whether to terminate the script or not.

5. Finally, execute the multi.php script as you did in step three. php multi.php

In the output below, you can see the message that tells you the current cron jobs count (63). Since the cron jobs count is more than 50, the script then terminates automatically and not proceed in adding cron jobs.

Terminating Script when reaching the Cron Jobs Count Limit

Conclusion

Throughout this tutorial, you’ve realized that PHP provides a way to automate cron jobs with the shell_exec() function. You’ve learned how to add, remove and list cron jobs in a single PHP script while ensuring you don’t overload your memory.

Now, will you consider PHP the next time you need to manage cron jobs for your projects?

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Источник

Оцените статью