When do I need to use cron? - php

Lets say there is a thread ( on forums ) which will be active for 3 days only. Now, after 3 days, I want this thread automatically closed.
Can I use reference to time when this thread is created in database, and than make if statement if current date + days is bigger than date created, I will print out "<h2>Thread Closed for posting</h2>"
And when I consider some other tasks, I suppose I can use reference to time and have certain event executed on this.
Am I right?

You can use a cron (ran every minute) to set a status field on the thread table to closed such as.
UPDATE threads
SET status='closed'
WHERE lastPost+INTERVAL 3 DAY<NOW()
Then in PHP something such as
if($thread['status'] == 'closed')
{
// Put your HTML here.
}

A 'cron' is a task that runs at a specific interval or time. This means that it should be used for tasks that must be done without user interaction. For example, a backup, automated emails or pulling data from a remote service.
What you want is better suited to a condition on checking whether a thread is closed. Rather than just having a flag, you also check the age. This means you can change your old-thread logic without needing to edit the database.

You could make a PHP script that gets executed by cron (read up on how to execute PHP in the command line) that SELECTs all the posts in a certain date and then sets them to closed. If you ran that, say, twice a day, then you could do a good job in getting all those posts closed.
Good reference on using cron to run PHP

Related

How to create a script that will run automatically every one hour and sends a curl request? [duplicate]

This question already has answers here:
How to set up a cron job to run an executable every hour?
(7 answers)
Closed 3 years ago.
I want to populate a hostoric database installed on a server. To do that I have to send multiple (curl)http requests on an endpoint changing the value of a certain field of a certain entity, also saved on a diffferent database. The problem is that I need to change the value of the field every hour for many days. I get it that people use cron jobs for this kind of task, but I need to know firstly in what language should I write the script preferrably(php, python, etc-with php being my personal preferred choice), or it does not simply matter and the important thing is to execute it via cron? Also what would the syntax for cron be in my scenario where I need to change the value every hour for say seven days?
Hi there are a lot of possibility to do cronjob, depends of your infrastructure. For example:
in a web-hosting with cpanel/plesk you can call a script (php for example)
you can also do cron by using user a starter, e.g. by creating a table on db with last execution on every user you can check the last execution and comparing it with actual time you can decide if start or not a scripts
you can create a crontab for your server in caso of managed server or vps (e.g. https://crontab-generator.org/)
you can use an online cron service. e.g. https://www.easycron.com/
and so on...

Running scheduled tasks in php [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a table, that consists of all the info to run a campaign. The info includes, the time interval to check the campaign (10 mins, 15 mins etc.) and other information to check whether it meets the specific requirement or not, to run the campaign.
At the moment, what I am planning to do is:
Add my code in one php file
In the code, go through all the rows of the table
Check if it's the time to check the campaign or not (via the interval)
If it's the time to check the campaign, then go through other details of the table and based on the set conditions, send an email or SMS.
I am planning to run a cron job which goes through this php file, after every 10 minutes (As it's the shortest check interval)
I need suggestions, whether it's the proper solution or not OR if someone has any better and efficient solution?
That's a decent starting point...
If it's the time to check the campaign...
Keep in mind that sometimes a cron process takes longer than expected, gets stuck or your system crashes in the middle. Ideally your process will keep track of a.) what it's doing, and b.) when it did it. And be able to fix problems like skipped or stuck processing.
It could be that you never want to send a message that late. Then again you may want to make sure all of the missed messages get sent. Your code should be able to handle this case automatically to some degree. Maybe automatically do anything that's should've been done in the last hour but wasn't and ignore anything older than that. For older stuff you'd have to manually run the script. Make sure your script has command line arguments that simplify you forcing it to run for prior time intervals and specific campaign IDs. This will make your life way easier after a disaster.
I suggest that you have some kind of reporting so you can keep track of your processing in real time. Pretty simple if you're writing state info to your database. Add on an end of processing timestamp and you can even see how long your cron jobs are running. If you don't want to use this state info in your cron job you can just write it to a log file instead of a database. And in that case (if needed) you would use a lock file to indicate when a cron job is running and prevent other cron jobs from starting at the same time. Regardless, it's good practice to write a log file so you have a record of what happened. Imagine if your cron job sent an email but crashed while attempting to write the state to the database. You'd at least have a log line to help you investigate later.
I am planning to run a cron job which goes through this php file,
after every 10 minutes (As it's the shortest check interval)
So the speed of your script will vary with the amount of data, latency of external services (assuming your script talks directly to such services). I would start with a much longer cron job start interval - assuming that your client/use case allows for that. If you follow the suggestion above to have your script automatically handle skipped times this isn't a problem. The more stuff you're processing the more time your script will eventually need. So on day 1 it might only need 1 second. But on day 300 it might need 15 minutes? (At that point you could decide that you want to have multiple processes/threads running at the same time with each one focused on a single campaign or range of campaigns. Who knows...) But you'll know because you have reports/alerts/logs on the start/end processing times.

"php script"/"mysql update" dynamic schedule

Hello fellow programmers! :)
I want to be able to set up some php script to be run after some events, triggered by user. Let's say, user creates a forum thread, that should be closed after 48 hours automatically. It is equivalent to an update to MySQL row:
UPDATE threads SET closed = '1' WHERE threads.id = 'x'.
Hence, this problem should not necessarily be solved exclusively with php.
This kind of questions pop up from time to time, but everything I found was to set up a cron job to run every 'x' amount of time, that checks if the time has come to close the thread. The problem is, that running this checks often cause higher system load than if you schedule a script to be run once at a given time. Not to forget, that there could be hundreds or even thousands of threads, each with it's own time to be closed. We can avoid checking every single thread by creating some sort of queue, for instance in MySQL, so the script selects from the DB entries with "time_to_close < NOW()" and closes these. Another drawback is, that I would like the thread to be closed exactly after 48 hours. In that case the script should be run every second and should take very little time to be executed completely.
Alternatively to cron job I think following method can also be useful:
check at every access to the Thread if it should be closed. This also causes higher load, especially if the thread is accessed very often.
So is there any efficient way to schedule a (php) script run depending on the time of a specific event? While writing this question I stumbled upon MySQL event scheduler. Together with procedures, that can provide additional flow control (close thread only if there was no activity since 48 hours) I think my idea can be implemented. I am not familiar with these functions of MySQL, so I would appreciate any help on this topic.
With best regards,
system__failure.
I know a lot of websites compensate for this kind of behavior by doing this on a per user request basis. The overhead is not that bad and your records are always displaying correctly (unless you have a design problem.) This also works because most hosts don't give you cron access. It is very rare you will need to schedule a job in php. There are a few exceptions like report generations every hour. But trying to catch user actions with cron is not a good idea.

Posting data from database at regular time intervals automatically in php

I have questions stored in my database. I want to regularly post one question on my website from the database at a 24 hr interval automatically. Is there a way I can do that ?
You can do this with steps:
Create normal PHP-script which will post your questions.
Schedule your script with standard OS scheduler. It is cron for *nix (Win-versions exist too) or AT for Windows. To define certain interval - you should read scheduler's manual (for cron format is provided here)
Example (cron)
0 2 * * * /usr/bin/php /path/to/insert/script.php
-in this case every day at 02:00 AM cron will try to execute command /usr/bin/php /path/to/insert/script.php - i.e. if your script.php will extract your question from DB and post it - that will do the stuff.
Yes you can do it by using Cron job . Set time interval and your file script location. It will automatically hit your script on that time interval.
Here is good tutorial : http://docs.phplist.com/SetupCronJob.html
Providing you could create a PHP script to select a different question each time, all you'd need to do would be to set up a cron to run the PHP script every 24 hours. You can find more info on cron here.
You should look into MySQL date functions.
A contrived example would be using CURDATE():
SELECT * FROM questions WHERE publish_date = CURDATE()
Storing the publish_date will mean you can dynamically load the question when that date arrives.
The only way to do it correctly is to use cron jobs. You should take a look at the administration panel of your hosting service.
Write a script that will post one question on your website everyday and set a cron job to run that script once a day and you are done.
How to set a cron job , ask you hosting service provider , most of the hosts have this feature in cpanel
Yes, you can. I will shortly outline the two most common solutions. The difficulty rises that PHP is not an always running program, but is a language executed on request and then shutdown on completion.
Have some sort of init.php file on your webserver which is being included on every page. That script will check whether the time has passed since last question, and push a new question.
On the other hand, you can add a cronjob which will execute your php script pushing the question. This solution is more robust, but requires access to a webserver you might not have.
Create a php file put the code to fetch question form your database
then set cronjob to excecute the file on perticular time or also
you can execute file by including it your login or any other page which
lods first by including that php file file so that when first user logs in
it will execute.
Steps
Create a PHP script to select and post a particular question randomly.
In your main php script write an AJAX method(which will load the PHP script) which can be called using setInterval() using the following syntax-
setInterval("AJAX_fun()", 24*3600*1000);
This statement will call the AJAX function in a periodic interval of 24hrs. For that you must know AJAX. I mean what should be the body of the AJAX to load the PHP script that you must have an idea of.
Another alternative
You can simply reload the page using javascript setInterval() function
i.e. <script>setInterval("window.location.reload()", 24*3600*1000);</script> and before that you have to select a question from the database randomly using a PHP logic.

Automatically execute MySQL query or PHP script without cron

So, I have a forum and I want to reward users who donated automatically with a special membergoup, I can do this by adding it into forum's MySQL database. What I need now is to remove such usergroup when a month has passed, automatically. What I would like to know is if it would be possible to make it purely on PHP for example, or another similar alternative.
Thanks in advance
php has no job scheduling mechanism built into it, unless you run a script as a daemon. MySQL has its own scheduling mechanism: http://dev.mysql.com/doc/refman/5.1/en/events-overview.html
You could store the date that the donation was made, and then, you could check the difference between that date and the current date.
If the result is > month then the user should not be in that membergroup.
Also, to avoid calculating that difference every single time, you could have an extra field in your database for each user, which would indicate if that user should be considered a donator.

Categories