How to send mail in php at scheduled time? - php

I want to build an application that enables users to schedule emails to send any time. simply, write email message and schedule it so that the server sends it at time specified. I am using zend framework. How to do it in php? Can it be done with cron jobs? If yes, then what are the disadvantages of using cron?

can it be done with cron jobs?
Cron is a time-based job scheduler in Unix-like computer operating systems. The name cron comes from the word "chronos", Greek for "time".1 Cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates. It is commonly used to automate system maintenance or administration, though its general-purpose nature means that it can be used for other purposes, such as connecting to the Internet and downloading email.
http://ubuntuforums.org/showthread.php?t=586478
I would run a cron job every minute and check if there are any mails ready to be scheduled. The quote from the forum topic below instructs how to run cron every minute.
crontab -e
then set a tab like
* * * * * /command
The first star is the minute section,
so having a star there will execute
every minute
In case it makes it more clear if you
wanted every 5 mins then it would be
*/5 * * * * /command/to/execute
And the other stars are from left to
right
minute hour dayofmonth month
dayofweek*
*0=sunday
Disadvantages of cron?
if yes, then what are the
disadvantages of using cron
When doing a lot of cronjobs you will have to spawn a lot of processes(pay cost of spawning process which is expensive). In that case it would be better to have background process(es) running continually and fetch messages from message queue. But when you want to run a cronjob only ever minute than I assume this will not be a big case.

I would tackle this using a cron job.
Simply create a script that checks for messages to send at a certain time. The user schedules for say 1PM (using a database of course), the script runs every 5 min, or so, and it checks (the db), are there any messages to go out for the current time? If so, it sends out the emails, else it sleeps.
Clean and simple way of handling it.
Disadvantages?
I can't see any, this is what a cron is made for, running tasks at specific times.

Related

Scheduled events in web development

I am working on a web application that requires php code to run at a specific date/time.
Some hypothetical examples would be sending a user an email at 09:00 on their birthday or modifying a database entry (mySQL) at a predetermined date and time.
What would be the conventional way to implement this kind of scheduling feature?
I've seen cron-jobs been used for similar requirements but would this be feasible for a large amount of scheduled tasks?
Depends on the size of your project, but usually we don't have one script do all the cron jobs, because things need to happen at different times. Some emails might send at 9pm, some database cleanup might happen at midnight, and sessions might expire every few minutes. The best thing to do is set up separate cron jobs for each thing. There are a couple exceptions for this:
Some tasks need to run very frequently, like every 30 seconds. For that we set up a cron task which checks "ps" to see whether its own process is already running, and have it just wait 30 seconds and loop.
Some tasks make more sense to run when a queue is full. For that we trigger the task when a certain user-based script executes the 100th or 200th or 300th time. For example when a user pings 100 times without doing anything else, we log them out without using a cron task, but there is a separate cron task which checks if they've been inactive for 10 minutes.

Automatic Mail Sending on specific Dates in PHP

I am having some mail ids in my database. I have to send mail to those mail ids automatically on some specific dates that i have mentioned in my database.How to do that in php.
It depends on your server type. If you use linux you can use cronjobs to program the execution of a specific php file at a certain time.
If you are hosted, your host may offer a cronjob menu in their cpanel, else you would have to get a better hosting plan that offer that. Or at least access to crontab file where you program the different Cronjobs.
Executing a PHP script with a CRON Job
You need to write cron jobs for sending the automatic emails on a particular date. Without this it is not possible.
Syntax
Here is a simple cron job:
10 * * * * /usr/bin/php /www/virtual/username/cron.php > /dev/null 2>&1
There are two main parts:
The first part is "10 * * * *". This is where we schedule the timer.
The rest of the line is the command as it would run from the command line.
The command itself in this example has three parts:
"/usr/bin/php". PHP scripts usually are not executable by themselves. Therefore we need to run it through the PHP parser.
"/www/virtual/username/cron.php". This is just the path to the script.
"> /dev/null 2>&1". This part is handling the output of the script.
Timing Syntax
This is the first part of the cron job string, as mentioned above. It determines how often and when the cron job is going to run.
It consists of five parts:
minute
hour
day of month
month
day of week
Or
You can set the cron in you cpanel.
Here are a few general steps of the logic that you can follow:
The PHP script should:
extract the email addresses and the specific dates from your database
into arrays.
check whether
today's date is
in the array containing the dates. Be sure to format the date appropriately!
loop through the email addresses (preferably in a foreach() loop),
if the above check returns 'true'.
within this loop, use PHP's mail() function to send your email.
Your next step would be to set up a scheduled task that runs this script daily, usually by means of a cron job. This step depends on the server you've got.
NOTE: These steps illustrate the most basic way to do what you require. There may be other, more complex ways that would be faster, cleaner and less intensive on your server.
As answered by Albert James it depends on the system type on which your application is running. If it is Linux then you can get the php script which send mail executed by cron jobs and if you are using windows machine then you need to execute that php script with schedule task : How to run a PHP file in a scheduled task (Windows Task Scheduler)
Also here is the option if you don't want to use schedule task\cron jobs (Though I haven't used that): How to send schedule emails using php without cron job
The software utility Cron is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals.
example

Creating multiple cron jobs with PHP

I'm in need of a way to create dynamic, one-off cron jobs to execute tasks at different times. Ideally, I would like to achieve this using PHP, so that when a user completes a certain action, the cron job is created and scheduled for a time that is calculated based on the time that the user completes said action. At any one time, there could be multiple cron jobs scheduled at once for different times. These cron jobs also need to be deleted upon completion.
I have tried searching around for something appropriate, however haven't encountered anything that works as I need. If anybody could point me in the right direction, that would be greatly appreciated.
Cheers
A possible solution:
Setting a Cron job that calls to CronJobManager.php every second.
Just make a regular daemon that calls for the CronJobManager.php.
Create a cronjob table in your database
The cron job table should contain these basic fields: path (to php file), run_time(datetime), last run (datetime) and type (like suicidal, if as you explain you want some cron jobs to delete themselves)
Connect CronJobManager.php with the cronjob table
Every time CronJobManager.php runs (that is, every second), loads the cron jobs. Then, comparing "now"'s time with each cron job's run_time you'll get which cron jobs to run.
For example, if cron job "foo" run_time is set to 18/04/2014 22:02:01, CronJobManager will run it when reaching that moment.
Notice that if Cron jobs executing time needs a lot of time, they'll get delayed and eventually a second or two will get lost.
Now, for every cron job that needs an execution, you would execute the related php file of that cron job, indicated in the path.
This is a general idea, and of course you would have to extend it with for example cron job states (idle, running, stop, etc).
In order to delete cron jobs you would implement this feature in the cron job object.
That is: the Cron Job class, once it has executed what it had to do, it would check its type (as defined in database). If it is 'suicidal', then it would delete the database row.
UPDATE
I updated the answer but I want to note something. If what you need is several cron jobs to run at once, in a specific second with 0 delay, then you need a cron job per task out of php that runs a specific file.
To achieve this functionality, you need to have a daemon that is running all the time that checks for these dynamic jobs and launches them. The setup is a tad complicated to put together, but if you are ready for such an endeavor, you can use the project PHP Resque Scheduler.
https://github.com/chrisboulton/php-resque-scheduler
You start up a daemon that runs all the time and then you can add jobs to a dynamic queue to be executed at any specified time in the future. I think you will find this suitable to everything you are looking to do.

Send mails with PHP regularly at a specific time

I have three mysql tables; Users, Tasks and Task_Users, where each user can create their tasks through a web application I'm developing in PHP.
The thing is, I want my application to send an email to the users one day before the task occurs. The first thing that came to my mind was to do a MySQL job or trigger to send the email but I dont have an idea of how to do id,
What would be the best way make this happen or how could I call a job through PHP and execute it every day and verify that there is just one day left before the taks ocurrs and then if that is true send the email?
Here's my table definition. Thanks in advance.
Users
----------
UserId,Names,email,pass
Tasks
------------
TaskId,TaskName,Descripcion,TaskDateTime
Tasks_Users
------------
TaskId,UserID
You can write a CRON Job for this.
What's CRON Job ?
Cron is the name of program that enables unix users to execute commands or
scripts (groups of commands) automatically at a specified time/date. It is
normally used for sys admin commands, like makewhatis, which builds a
search database for the man -k command, or for running a backup script,
but can be used for anything. A common use for it today is connecting to
the internet and downloading your email.
What do you have to do ?
Just write a normal PHP script. make one that will work if it's launched directly from the browser. Then schedule that very same PHP file to run in cron, using this as a guide:
How to run a CRON Job after it's written ?
http://www.inmotionhosting.com/support/edu/cpanel/301-run-cron-job
If you have any issues let me know.
I'd make a cron job that regularly runs a script (say every 5min?) which checks for tasks that need emails sent. Then the script script sends the necessary emails.
*/5 * * * * php /path/to/script.php
Would call script.php, which checks and sends emails, every 5minutes.
Some info on cron is here:
http://www.pantz.org/software/cron/croninfo.html

Limit to cron job with PHP

I have a Cron Job with PHP which I want to set up on my webhost, but at the moment the script takes about 20 seconds to run with only 3 users data being refreshed. If I get a 1000 users - gonna take ages. Is there an alternative to Cron Job? Will my web host let me run a cron job which takes, for example, 10 minutes to run?
Your cron job can be as long as you want.
The main problem for you is that you must ensure the next cron job execution is not occuring while the first one is still running. You have a lot of solutions to avoid it, basically use a semaphore.
It can be a lock file, a record in database. Your cron job should check if the previous one is finished or not. A good thing is maybe sending you an email if he cannot run because of a long previous job (this way you'll have some notice alerting you that something is maybe getting wrong) By default cron jobs with bad error dstatus on exit are outputing all the standard output to the email of the account running the job, depending on how is configured the platform you could use this behavior or build an smtp connexion on the job (or store the alert in a database table).
If you want some alternatives to cron jobs you should have a look at work queues. You can mix work queues with a cron job, or use work queue in apache-php envirronment, lot of solutions, but the main idea is to make on single queue of things that should be done, and execute them one after the other (but be careful, if you handle theses tasks very slowly you'll get a big fat waiting queue).
A cron job shouldn't have any bearing on how long it's 'job' takes to complete. If you're jobs are taking 20 seconds to complete, it's PHP's fault, not cronjob.
Will my web host let me run a cron job which takes, for example, 10 minutes to run?
Ask your webhost.
If you want to learn about optimizing php scripts, take a look at Profiling PHP Code.

Categories