Tuesday 22 December 2015

How to run PHP program using Windows Task Scheduler.

Step 1: First of all we’ll write a simple PHP program to "create/write" new file.

<?php
        error_reporting(0);
        $root = "D:\www\pcwf"; //location
        $filename = date('H-i-s') . ".txt"; // name of .txt file
        $folder = $root . '/cronjob/' . $filename;
        $f = fopen($folder, 'w');
        $fw = fwrite($f, 'now : ' . $filename);
        fclose($f);
?>

Note that the location of my script is : “D:\www\kj.php”

Step 2: Now, Go to Start > All Programs > Accessories > System Tools > Task Scheduler.

Step 3: Click on Task Scheduler Library. Now Create Task using action menu.

Step 4: On Create Task window you can see multiple tabs i.e General, Triggers, Actions, Conditions & Settings.

Step 5: After clicking on “Create Task” the default “General” tab will appear. Provide name and description of your task there.

Ex. Name: “Testcron”, Description: “Test Cron Job”

Step 6: Now click on “Triggers” tab

Step 7: And schedule task from here.

Ex: Here I’ve scheduled my task on 12/21/2015 11:54:00 AM for duration of 1 day (see “Daily” radio button) and after trigger it’ll repeat every 1 minute (See Advanced setting)

So we’ve scheduled our task (At 11.54 AM every day –After triggered, repeat every 00:01:00 for a duration of 1 day). Now must specify the action that will occur when task starts i.e. to run our PHP script (See Step 1)

Step 8: Click on “Actions” -> New -> Select Action: “Start a program” from dropdown field

Step 9: In “Program/script” field provide path of “php.exe” (Ex: Here I’ve provided “C:\php\php.exe”) and In “Add arguments” provide path of PHP script (In Step 1) i.e. “D:\www\kj.php”

Click “OK” and provide credential of system (in case it prompts). Finally you’ll see:

Step 10: Now check the path where we are writing our file.

Here, the task will trigger after every 1 min and script will write new file.

That’s it!!

Hope it helps.

Thanks.