I'm creating a website and in my website I have a MySQL database. In the database there is a table that has two property "date" and "time". I want to run a php code on a date and time according to records of table, automatically. How can I do it?
I see three options, listed here in order of difficulty to implement, easiest to hardest.
Create a script that is scheduled to execute every now and then (exact timing would depend on your needs for accuracy), which checks the database to see if there are any items in there that should have been executed in the time span since it's last execution. If there are, execute them.
Write a daemon application/script to monitor your database, and execute the tasks when needed. This one is not all that different from #1 except that it wouldn't require scheduling or manual triggering. That could be handled within the application/script itself.
Create a script that checks the database for changes, and schedules/reschedules/removes any tasks accordingly. This script would then be scheduled to execute every now and then and/or be executed manually by the application that manages the database.
Write a php script (that queries the database and runs the script) powered by crontab (for periodically running your 'query'-script) in a shell (on linux)
Related
Let's say a website who needs to display the updated content every 5 minutes. For sure we can use a cron job to schedule a PHP script like
$weather = file_get_contents("https://weather.com/country/state/city/day/hour/minute.json");
$upload_to_database = send_data_to_db();
Let's say this simple script takes the data and send it to the MYSQL and then the data is being displayed on frontend by fetching data using AJAX every few minutes or maybe sending the notifications after analyzing the data and so on...
Now, what if we have thousands of cities. How can I create cron jobs for those cities automatically?
I hope you did understand my question.
Another example can be SERP Rank tracker for thousands of keywords and so on...
Instead of creating many separate cron jobs which each do one retrieve/update job, just create one generic cron job which does all the retrieval/updating work.
If you want them to run independently and simultaneously, you could spawn separate processes from that one cron job. You could do that dynamically from PHP, so you can use a current list of cities and spawn a separate process for each.
For example, instead of running "php updatecity.php Washington" (as an example of how you run your php script that updates a particular city), run this:
nohup php updatecity.php "$city" > /dev/null 2>&1 &
This will launch a separate php process silently in the background, running your updatecity.php script with a $city parameter as argument.
Make sure your processes cannot stall or keep running, otherwise you may end up flooding your server with tons of unterminated processes.
I have a database with variables I want to change depending on the date. The events in the database have dates. After this date I would like to set a variable 'past' to true. Meaning, the event has past. How can I approach this with php or is this something that needs to be added to the database itself (using phpMyAdmin) ?
Naturally, you first need code that does the actual update. This could very well be a PHP script, but you probably won't want to embed it into a web page, but to run it from the command line (see below).
Secondly, you need to execute that code on a regular basis so every update is done within a guaranteed time span after the event has passed. To execute scripts or other code regularly, you can use cron (if you are on Linux) and similar mechanisms.
If you need to make sure that the updates are done as fast as possible after the respective event has passed, you will need to write a full-blown daemon which runs in the background and does its checks 10 times per second, for example, or (instead of polling) uses appropriately programmed one-shot timers.
If you insist on writing the script in PHP and don't want to run it from the command line (as required by cron for example), you still can embed your code into a web page as usual and then use tools like wget or curl in conjunction with cron to retrieve that web page and get your code executed regularly.
I have a database that has 20 rows each row I had set a Boolean value to it, so it is by default zero and when a row gets viewed its value changes to 1
I want the database to send any kind of signal that when 10 rows their value change from zero to 1, a certain PHP file fires up and starts a process that will affect only these 10 rows
How can I do that?
Thanks in advance
I would say, query from the php file every set amount of time to your database
The other way, database to execute a php file is almost impossible.
If you are using mySQL as database, a trigger could invoke the sys_exec() UDF available here: https://github.com/mysqludf/lib_mysqludf_sys#readme
So, there might be a possibility, actually, via an UDF function that would launch the php executable/script; not that easy, but seems possible ;-)
Invoking php from mysql is impossible, all you can do is set cron jobs for it. Cron job check mysql after certain interval of time and run the respected code
Every database is only a storage and it is its purpose in the system. Don't try to trigger any external process by the storage. The communication with the storage should be only a one way.
Rather think how to trigger your process from outside. Generally, there are two approaches:
a script that will check your database data in some interval like 1s, 10s, 1min or whatever would fit for a particular process
the current process that is updating your data can check your data and trigger another process if needed.
You can not trigger external file/script from mysql.
What you can do is create a cron job which run after certain interval of time which check database and perform certain operations.
I have to populate and update one of my MySql database table using a complex and expensive query, based on selection from other table's data. This table doesn't need to be always fully updated when i make a query on it, but i'd like to have a cyclic update every 5 minutes.
This automatic update should be infinite and i need to be sure that it never stops.
After some research, i've found some solution, but i don't know which is better for security and performance.
One of these could be my goal:
Don't create table and make complex query from php every time to get the desired result
Create a php script that repeats cyclically and update table db, maybe using Cron Job.
Update table using a sql event
I think that first solution could be to expensive since query is complex and there could be many request every second, but the result is always updated. I don't have experience about Cron Job, so i can't know if it could be a good idea or not. For the third solution, i still don't have database privileges to run events, but i'd like to know if it could be a valid solution.
All other solutions are welcome, thanks.
Do not use cron. Think about what will happen if one instance goes beyond 5 minutes and the next starts up. Eventually you will have hundreds of copies bogged down stumbling over each other.
Instead have a single job in a loop doing the update. (OK, you could have a cron job to perform a "keep-alive" task of restarting the query if it dies.)
The job would
CREATE TABLE new ...
INSERT INTO new SELECT complex-stuff...
RENAME TABLE real TO old, new TO real;
DROP TABLE old;
loop.
I would opt for Cron Job.
It doesn't clog any request, since it's executed from the operating system.
You can define which user executes the script (cron -u apache -e).
Easy to define interval. (i.e. every 5 minutes */5 * * * * php /path/to/script.php).
It's loggable.
Additional Notes
I had a cron job running under root and it worked just fine. My problem was that the project had a private logging mechanism that each log file would be created by apache user. By running it from root, sometimes the file would be created by root and after that, the scripts being executed by apache would not be able to APPEND to the log.
I also had an emailing script that would run once every 2 minutes that got stuck for 1h. Turns out, because of a bug in the application, an invalid email address (somethingwithoutatsign.com) was inserted into the database, which made the PHPMailer library throws errors. After that, I added a catch block that would send an email to me whenever an exception was thrown. Now, if the script stops running because of bad execution, I get to know right away.
My host (blueangelhost.com) claims that I can't use the event scheduler because it takes up too many resources. I have access to cron jobs in cPanel, but I've tried and they don't seem to work.
So, my question: Is there any kind of efficient PHP code that will automatically truncate a MySQL table in a database?
Well, if it needs to be automatic, or at a specific time, not really. But you could have your website trigger the script when someone gets on it, here's the approach you could use:
On a script that is run on every page (header, menu,footer, layout):
Check in DB or file, the date of the last truncate;
If the date is yesterday, run the truncate;
Change DB or file and put current date;
This way, it will execute once a day. But never at the same time, and not if no one walks on your website for a whole day.