Home >php教程 >PHP开发 >Simple real-time database monitoring and scheduling through PHP CLI

Simple real-time database monitoring and scheduling through PHP CLI

黄舟
黄舟Original
2016-12-14 13:17:061352browse

Function to be implemented: Monitor the user table. If a new record is added, add it to the user2 table. (Practical applications can be more in-depth, such as related processing of data, etc.)

The following is the PHP code (dbtest.php)

The code is as follows:
!#/usr/local/php/bin/php
mysql_connect('localhost', 'username', 'password');
mysql_select_db("test");
echo 'PID: '.posix_getpid().' '; //Current process PID (under linux)
$ old_id = 0;
while (1)
{
$sql = "SELECT `id` FROM `user` ORDER BY `id` DESC LIMIT 1";
$result = mysql_query($sql);
$item = mysql_fetch_assoc( $result);
$new_id = $item['id'];
$values_arr = array();
for ($i=$new_id; $i>$old_id && $old_id!=0; $i--)
{
$sql = "SELECT `name`,`age` FROM `user` WHERE `id`='{$i}' LIMIT 1";
$result = mysql_query($sql);
$item = mysql_fetch_assoc( $result);
$name = $item['name'];
$age = $item['age'];
$values_arr[] = "('{$name}', '{$age}') ";
}
if (!emptyempty($values_arr))
{
$values_str = implode(',', $values_arr);
$sql = "INSERT INTO `user2`(`name`, `age`) VALUES {$values_str}";
mysql_query($sql);
}
$old_id = max($old_id, $new_id);
sleep(3); //Enter the next loop after 3 seconds
}

Business process should There is nothing to say, but there are a few things to pay attention to:
The first line is the command path that needs to be added in PHP CLI mode, and there are while(1) and sleep(3). The rest are ordinary PHP code writing methods.
Just run it through the shell command php dbtest.php. I tested it on a virtual machine. Under normal circumstances, the CPU usage is 0% and the memory is 1%.
In actual applications, it can be run in the background:
php dbtest.php &
bg 1
PS: The & command is unclear or even wrong in many places. It just puts the program in the background without actually running it!
By the way, let’s summarize and review the commands related to Linux’s front and back operations

How to use the front and back status of the command

& background pause is added after the command

bg background running is followed by the job number

fg foreground running is followed by the job number

Ctrl+Z Background pause (key combination)

jobs (view all job numbers) command

For more related articles, please pay attention to the php Chinese website (www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn