In this tutorial, you will be learning to create and run cron jobs on localhost. You will need XAMPP or WAMP and this tutorial is for Windows OS only. We will be creating a cron job that will insert a new row in database once a day. We will be using Windows Task Scheduler to tell which file to execute as a cron jobs.
Insert row in database
Create a simple file named index.php and write the PHP code to insert a new row every time that file executes. We have created a sample database called my_db and it has only 1 table called my_table and that table has only 1 column called current_date.
<?php // Connecting with database $connection = mysqli_connect("localhost", "root", "", "my_db"); // Getting current date $date_time = date("Y-m-d"); // Inserting in database mysqli_query($connection, "INSERT INTO my_table(current_date) VALUES('$date_time')");
Creating script.bat file for windows Task Scehduler
Script.bat is the file that will tell the windows task scheduler which file to execute as a cron job. In this file, you have to tell the path to your php.exe file which is located in your XAMPP or WAMP “php” folder and the path to your index.php file. Create a simple file named script.bat and paste the following code in it:
"path_to_php.exe" -f "path_to_index.php"
Creating a VBS file
A VBS file should be created that will tell the path of script.bat file. Create a new file named shell.vbs and paste the following code in it:
'Starts a new windows shell process (command line). Set WinScriptHost = CreateObject("WScript.Shell") 'Runs a command and sets the character set for the text string, "script.bat" WinScriptHost.Run Chr(34) & "script.bat" & Chr(34), 0 'Tells the shell not to display the window. Set WinScriptHost = Nothing
Setting up Task Scheduler
You can follow the video below to setup the task scheduler in your windows:
That’s how you can run cron jobs on your localhost in windows operating system. If you face any problem in following this, kindly do let us know.
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post