1

我对创建服务器每天运行的服务器脚本和作业相当陌生。

我的问题如下:

我想向我的用户发送一封电子邮件,提醒他们必须完成的特定工作。

我的想法:

数据库 -> 收集所有需要通知的用户并将他们插入到表中notify_user

脚本 -> 查找所有用户并向他们发送邮件

脚本 -> 从表中删除所有

然后,此脚本将在每天的特定时间运行,例如每 24 小时运行一次。

正如我之前所说,我并不热衷于如何设置这样的脚本。

我的服务器是 Ubuntu 服务器,我的应用程序是 PHP 程序。

有谁知道我如何实现这一点,或者知道我在哪里可以找到关于这个主题的一些文档,因为我找不到任何可以解决这个问题的东西。

4

1 回答 1

1

如果您知道如何填充“notify_user”表,那么这些是我为您重现解决方案示例的步骤。我在运行 sendmail 守护程序的 VPS 服务器上执行此操作。

# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 167
Server version: 5.5.40-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>  create database stack_mail_db;
Query OK, 1 row affec`enter code here`ted (0.05 sec)
mysql> grant all privileges on stack_mail_db.* to 'stack_mail_usr'@'localhost' identified by 'stack_mail_pass';
Query OK, 0 rows affected (0.11 sec)
mysql> use stack_mail_db;
Database changed
mysql> create table notify_user( id int not null auto_increment primary key, user_name tinytext, user_email tinytext );
Query OK, 0 rows affected (0.28 sec)

创建此示例数据库后,我们应该使用至少 2 个用户(用于测试)填充工作电子邮件。我在这里更改了我使用的实际电子邮件。

mysql> insert notify_user (user_name, user_email) values ('test1', 'test1@test.com');
Query OK, 1 row affected (0.18 sec)

mysql> insert notify_user (user_name, user_email) values ('test2', 'test2@test.net');
Query OK, 1 row affected (0.03 sec)

现在我们应该编写一个脚本来获取这些详细信息并发送电子邮件:

# vim cron_email.php
<?php
$host = 'localhost';
$user = 'stack_mail_usr';
$pass = 'stack_mail_pass';
$dbname = 'stack_mail_db';

$conn = new mysqli($host, $user, $pass, $dbname);

if ($conn->connect_error) {
        trigger_error('DB connection failed: ' . $conn->connect_error, E_USER_ERROR);
}

$query = 'select * from notify_user';

$res = $conn->query($query);

if ($res === false) {
        trigger_error('Failed query: ' . $query . ' Error: ' . $conn->error, E_USER_ERROR);
}

$headers = 'From: admin@example.com' . "\r\n" .
        'Reply-To: admin@example.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
$res->data_seek(0);
while ($row = $res->fetch_assoc()) {
        $to = $row['user_email'];
        $subject = 'Notification for ' . $row['user_name'];
        $message = 'Hello ' . $row['user_name'];
        $mail = mail($to, $subject, $message, $headers);
        if ($mail) {
                $conn->query('delete from notify_user where id=' . $row['id']);
        } else {
                echo "Email failed\n";
        }
}

现在是时候将这个脚本放在 cron 上:

# crontab -e
0 0 * * * php -f /path/to/cron_email.php

这将在每个午夜运行您的脚本。如果您想设置更具体的时间,请查看本教程: http ://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses /

希望这会有所帮助^)

于 2014-11-19T19:45:44.260 回答