This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join our live AMA on the Future of Page Builders with Brizy's CEO! Register Now →

How to Schedule Cron Jobs in PHP Using Cloudways

Updated on March 8, 2024

6 Min Read

Ever wished your tasks could run on autopilot? That’s where Cron Jobs step in, silently handling scheduled tasks in the background.

In today’s blog, we’re going to cover what Cron Jobs are in detail and how they work. We’ll also tell you how to schedule Cron Jobs using the Cloudways platform within a few clicks.

We’ll also point out 7 scenarios when Cron Jobs can be useful for you.

Let’s get started.

What Are Cron Jobs and How Do They Work?

A Cron Job is a Linux command designed for the automated scheduling of tasks or commands on a server. It enables users to automate the execution of scripts written in various programming languages, facilitating the efficient management of routine server tasks.

Cron jobs can be configured to run at specified intervals, such as every 15 minutes, hourly, on specific days of the week or month, or any combination of these timeframes. This flexibility allows users to automate repetitive tasks, enhancing the overall efficiency of site management.

Typically, a Cron Daemon, a background program that runs continuously, exists on Linux-based systems. This daemon is responsible for executing scheduled tasks based on the specifications provided. The configuration information, including timers and task details, is stored in a file known as ‘Crontab’.

Where Are Cron Jobs Executed in PHP?

Cron jobs are executed on the system where they are scheduled, typically on the server or machine running a Unix-like operating system. The execution location is not external — it occurs internally on the system where the cron job is defined and scheduled.

Cron Jobs are typically set up using the system’s crontab scheduler. To schedule a PHP script to run periodically, you need to add an entry to the crontab file. This file contains a list of commands and their schedules for execution.

Host PHP Websites with Ease [Starts at $11 Credit]

  • Free Staging
  • Free backup
  • PHP 8.3
  • Unlimited Websites

TRY NOW

How to Run a Cron Job in PHP?

To make it super simple to understand, here’s an overview of how to run a Cron Job in PHP:

  • Timing: Specify when the job should run by setting the weekday, month, day, hour, and minute.
  • Execute: Use the PHP interpreter located at /usr/bin/php to execute the PHP script.
  • Script Path: Provide the path to the PHP file you want to run.
  • Output: Choose whether to capture or discard the output. You can use /dev/null 2>&1 to discard the output.

Here’s an example of how you might schedule a PHP script using cron:

1. Open the crontab file for editing. You can do this by running the following command in the terminal:

crontab -e

2. Add a line specifying the schedule and the command to execute your PHP script. For example, to run a PHP script located at /path/to/your/script.php every day at 2:30 AM, you would add:

30 2 * * * /usr/bin/php /path/to/your/script.php

In this example:

  • 30 represents the minute (30th minute).
  • 2 represents the hour (2 AM).
  • The asterisks represent any day of the month, any month, and any day of the week.

3. Save and exit the crontab file.

This entry tells the cron daemon to execute the specified PHP script at the scheduled time.

How to Run Cron Jobs Using the Cloudways Platform?

Many hosting providers offer their own interface for adding cron jobs. Cloudways, which is a managed cloud hosting platform, also provides an option for adding cron jobs on its platform.

Here’s how you can use the Cloudways platform to schedule Cron jobs.

  • Log in to the Cloudways Platform using your credentials.

  • Navigate to the Applications section in the top menu bar and select the specific application you want to set up a cron job for.
  • Add a New Cron Job:
    • In the Cron Job Management section, click on the “Add New Cron Job” button.

  • Configure the Cron Job:
    • Determine the frequency of the cron job using the provided drop-down menu with predefined values or set a custom schedule.
      • Minute (Range: 0 to 59)
      • Hour (Range: 0 to 23)
      • Day of month (Range: 1 to 31)
      • Month (Range: 1 to 12)
      • Day of week (Range: 0 to 6, Sunday will count as 0)
    • Choose the type of script to run (PHP, curl, or wget) and specify the command to execute.
    • Click “Submit” to save your configuration.

  • View Your Cron Job:
    • Once configured, your cron job will be listed under the Basic tab.

  • Advanced Settings (Optional):
    • If you need to use command-line switches or apply advanced cron settings, switch to the Advanced tab.
    • Note that only account owners or team members with full privileges can edit cron jobs via the Advanced tab.
    • For wget and curl, switches are only allowed in the Advanced tab, not on the basic tab.

You might also like: How to host PHP on DigitalOcean using Cloudways

How to Block Untrusted Access to Cron Job?

When you write your cron job in a scripting language like PHP, you should make sure that it is inaccessible from the web browser. One of the approaches is to keep it away from the web root folder.

But most of the developers don’t do that. Another way is to block access from the .htaccess file. You should just block access by putting this line in the .htaccess file if you are keeping it in another folder other than the root.

deny from all

Another way of doing this is to put this line at the beginning of the page, but it will disable the use of wget or curl, so better not to use this:

if(issset($_SERVER['REMOTE_ADDR']))die('Permission denied.');

7 Scenarios When Cron Jobs Can Be Useful for You

As mentioned above, Cron jobs are more useful for server admins in general. However, for a  web developer, this feature can be useful in the following cases:

  • If you own a website that provides memberships, you can schedule cron jobs based on the expiration date. This allows you to either deactivate or delete accounts according to their expiry dates.
  • For blog owners, cron jobs are ideal for maximizing reach by automating newsletter emails.
  • To save every web page hit in a database table, you can rely on cron jobs. This helps in storing daily traffic summaries in your database.
  • Cron jobs can facilitate the erasure of cached data files.
  • If you are responsible for SEO and have concerns about broken links on your million-page website, cron jobs are perfect for auto-checking broken links and sending yourself a daily report.
  • Performing long-running tasks, such as sending emails in large volumes or encoding videos, can be efficiently handled through command line scripts executed by cron jobs.
  • For social media marketing specialists, cron jobs can assist in fetching recent tweets, which can be cached in a text file.

Conclusion

In this article, we have discussed what Cron jobs are and where they are used. Further, we discussed how the backend mechanism works and how to schedule Cron jobs in PHP using the Cloudways platform.

To test out the efficiency of Cron jobs yourself, sign up for your free trial of the Cloudways Managed PHP Hosting Platform today.

Q.1- How do I run a cron job in PHP?

A: Here are the steps to run a cron job in PHP on Cloudways:

  • Log in to your Cloudways platform.
  • Access the Cron Job section.
  • Click “Add Cron Job.”
  • Set the frequency for the cron job.
  • Provide the link to the script.
  • Click Apply to save the settings.
  • Your cron job is now scheduled and ready for use. If you prefer manual configuration, use the Advanced section. Keep in mind that steps may differ if you’re using cPanel.

Q.2- How to schedule a function in PHP?

A: Follow the steps below to schedule a function in PHP:

  • Log in to your server’s control panel.
  • Navigate to the cron job section.
  • Create a new cron job.
  • Specify the execution frequency.
  • Enter the PHP interpreter path.
  • Define the command with the script’s path.
  • Save the cron job settings.
  • Verify the scheduled function runs as expected.

Q.3- What is better than a cron job?

A: If you seek a free alternative to cron, consider options like systemd, anacron, cronie, fcron, bcron, and Airplane schedules.

Q.4- Are cron jobs secure?

A: While cron jobs themselves are generally secure, the security depends on the scripts they execute. If malicious users manipulate these scripts, it can pose a risk to the system’s security, potentially leading to broader vulnerabilities and compromises.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Ahmed Khan

Ahmed was a PHP community expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is a software engineer with extensive knowledge in PHP and SEO. He loves watching Game of Thrones is his free time. Follow Ahmed on Twitter to stay updated with his works.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now