Task scheduler php script

Automating PHP Using Task Scheduler

PHP is a request/response server platform. Users request data from the server maybe in the form of a link on a page, PHP goes out to the server before the new page loads (i.e. server-side) and a response is then sent back to the user. This architecture means that it can be very difficult to automate tasks for your applications as you are relying on user interaction. As we can execute PHP from the command line, I’ll show you how to integrate that within a program called Task Scheduler which will allow to execute a PHP file when it matches certain conditions and triggers.

Before we begin, please note that Task Scheduler is a Windows only solution. If your site runs on Linux, you will need to look at daemons and cronjobs which is out of the scope of this guide.

Читайте также:  Typescript оператор вопросительный знак

4 Step Walkthrough

  1. Setup a PHP Environment Variable (if required)
  2. Writing our PHP script
  3. Creating a BAT file which executes our PHP script
  4. Set up a task in Task Scheduler to execute the BAT file at certain times

1. Setup a PHP Environment Variable (if required)

You may have already done this step so skip it if you have. If you haven’t, firstly go to Control Panel > System and Security > System > Advanced System Settings .

Next click on Environment Variables (shown below).

Task scheduler php script

Next click on the Path under System Variables and click Edit. Then you need to add in the path to your PHP folder. In my case that would be C:\\Apache\\php .

Task scheduler php script

All variables declared in the field are separated by a semi-colon (;) so do not forget this when adding in your path. After you have added your PHP path, click OK, OK then Apply and then restart your computer. Once restarted you have successfully added your environment variable for PHP on your machine.

2. Writing our PHP script

This is the easy bit. I have already written a simple PHP script that will create a new text file each day, append the date to it’s filename and write a small string inside it. Nothing too complicated here. I have saved this in the root of my web projects folder but it could be located anywhere.

$today = date('Y-m-d'); $filename = 'text-file-' . $today . '.txt'; $file = fopen($filename, 'w'); fwrite($file, "Log for $today. "); fclose($file); 

3. Creating a BAT file which executes our PHP script

Open up Notepad and type the following:

# automatic.bat php C:\\Apache\\htdocs\\automatic.php 

The first part indicates that we want to execute a PHP script and the second part indicates the location of where my PHP file is located. In my case as mentioned earlier, in the root of my web projects folder. Now save the document as automatic.bat in the same location as your PHP file (doesn’t have to be but for simplicity’s sake).

To test what we have done so far, double-click the automatic.bat file you just created and you should see a text file created in the same directory with the date appended to the file name. Now we know that this is working, we can move on to the final step.

4. Set up a task in Task Scheduler to execute the BAT file at certain times

Task scheduler php script

Task scheduler php script

  • Open up Task Scheduler on your machine and click Create Basic Task. You can also click Create Task also but the Basic Task gives you a wizard which is great if you’ve never used Task Scheduler before.
  • Give the task a name and description and click Next.
  • Now select Daily as the Task Trigger and click Next.
  • Now select a date for the task to start executing and a time you would like it to occur. We want to leave Recur Every to 1 day as once a day is enough for our needs. Now click Next.
  • We want to Start A Program when this task initiates so select this and click Next.
  • Our Program/Script is our automatic.bat file we created earlier and I’ve added in the Start In parameter as my web projects folder. This is because when this executes; as I haven’t specified a full path in my PHP script as to where my text file gets created; it will create it in the same folder that the script resides in or is executed from.
  • Click Next to summarise and then click Finish.

Task scheduler php script

DONE!

You have successfully setup your task.

You are able to test that your script works by right-clicking on the task in Task Scheduler and clicking Run. Similarly, you can edit the rules of the task by clicking Properties.

I am no expert using Task Scheduler or the Command Line but hopefully this will help some users wanting to automate simple PHP tasks for their applications. It must be said that you are also able to write MySQL queries in your script file so you are not limited in terms of the type of automated scripts you want.

Источник

Schedule A PHP Script to Run At Specified Time (Windows Linux Mac)

Welcome to a tutorial on how to schedule a PHP script to run at a specific time. Need to send out emails at a set time? Or maybe to run an automated update script? Yes, we can schedule PHP scripts to run at a specified time on the various platforms using their respective schedulers. Read on to find out how!

TABLE OF CONTENTS

WINDOWS SCHEDULING

In this section, we will look at how to schedule a PHP script using the Task Scheduler in Windows.

WINDOWS TASK SCHEDULER

STEP 1) OPEN TASK SCHEDULER

STEP 2) CREATE TASK

STEP 3) GENERAL SETTINGS

Give your new task a name, and select “Run whether user is logged on or not”.

STEP 4) SET A TRIGGER TIME

Triggers > New > Set the script to run as desired – Once, repeat daily, weekly, or even monthly.

STEP 5) RUN PHP SCRIPT AS ACTION

Actions > New > Point the “Program/script” to php.exe > Add the script that you want to run under the arguments > OK.

Done. Your PHP script is now set to run on a schedule.

ALTERNATIVE – SCHEDULING WITH COMMAND LINE

If you need to schedule to run a script programmatically, try the command line schtasks :

  • TN Task name.
  • TR Task run.
  • SC Schedule ( MINUTE, HOURLY, DAILY, WEEKLY, MONTHLY, ONCE, ONLOGON, ONIDLE, ONEVENT ).
  • ST Start time.
  • SD Start date.

LINUX SCHEDULING

Moving on, let us look at how to schedule a PHP script in Linux.

SCHEDULING WITH AT (RUN ONCE)

echo "php /PATH/TO/script.php" | at 1:23 PM 12/12/2012

Linux comes in various different builds and flavors, some may offer a graphical interface to schedule tasks while some don’t. So we will go straight into the most reliable way – Using the command line. To schedule a task to run once only, we use the at command.

SCHEDULING WITH CRON (RUN PERIODICALLY)

sudo crontab -e 0 3 * * * /usr/bin/php /http/test.php
  • Minute – 0 to 59
  • Hour – 0 to 23
  • Day of month – 1 to 31
  • Month of year – Either 1 to 12, or Jan to Dec
  • Day of week – 0 to 6, or Sun to Sat
  • Command to run

So for the above example, the PHP script is set to run at 3 AM every day in morning. If you need more crontab examples, I will leave a link in the extras section below.

P.S. You can also use crontab -l to list all the existing scheduled tasks, crontab -r to stop all cron jobs.

MAC SCHEDULING

Well, macOS is Unix-based. Meaning, using the good old crontab again.

SCHEDULING WITH CRON

crontab -e 30 5 * * 1 /usr/bin/php /http/test.php

Yes, it’s the same as Linux. But here is just another example that will run at 5:30 AM every Monday.

SCHEDULING WITH GUI

  • Using Automator to create an “auto-run PHP shell script” workflow.
  • Then use iCal to schedule run the Automator task.

I am not a Mac guru, so do your own research… Crontab is just a lot easier though.

PLATFORM INDEPENDENT SCHEDULING

So what do we do when we have no access to a task scheduler? Here is a final alternative.

INFINITE WHILE LOOP “SCHEDULER”

= $runAT) < // (B1) DO YOUR STUFF HERE echo "Running!"; // (B2) STOP LOOPING break; >sleep(10); // WAIT FOR X SECONDS >

Simply run this script in the command line or use exec(«PHP SCHEDULER.PHP») to launch it. This script will simply keep looping until it hits the preset $runAT to run whatever is required.

P.S. Beware though, many instances of this script can be spawned. You might want to create some kind of “locking mechanism” to prevent too many from running.

P.P.S. Some “master code trolls” are not going to be happy with this “stupid dangerous endless loop alternative”. But if all else fails and this is the only one that works – Then it’s a good solution.

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Источник

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