You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中结合自定义JS时钟实现随机服务启停事件触发方案咨询

实现方案

1. 前置准备:创建事件存储表

首先生成Laravel迁移文件创建任务事件表,执行命令:
php artisan make:migration create_task_events_table
编辑迁移文件的up方法:

public function up()
{
    Schema::create('task_events', function (Blueprint $table) {
        $table->id();
        $table->time('prog_time'); // 对应PROGTIME 自定义时钟时间
        $table->enum('event', ['START', 'STOP']); // 事件类型
        $table->string('message'); // 事件消息
        $table->datetime('actual_time'); // 实际系统时间
        $table->string('display_message'); // 展示用文本
        $table->timestamps();
    });
}

执行迁移生效:
php artisan migrate

2. 封装自定义时钟换算逻辑

在app/Helpers目录下新建通用函数文件(无该目录可自行创建,之后在composer.json的autoload字段中注册目录即可),实现不受系统时钟影响的自定义时间换算逻辑:

// 计算自定义时钟的当前时间(固定从当日7点开始计时)
function getCustomProgTime(): array
{
    $todaySevenAm = Carbon::today()->addHours(7)->timestamp;
    $nowTimestamp = Carbon::now()->timestamp;
    // 计算自定义时钟已运行秒数,跨天则取模24小时
    $runSeconds = ($nowTimestamp - $todaySevenAm) % 86400;
    // 负数说明还未到当日7点,加86400取前一天的运行时长
    if ($runSeconds < 0) $runSeconds += 86400;
    // 转换为时分秒格式
    $progTime = gmdate('H:i:s', $runSeconds);
    return [
        'run_seconds' => $runSeconds,
        'prog_time' => $progTime,
    ];
}

3. 编写事件生成逻辑

创建Laravel自定义命令,用于秒级轮询触发任务:
php artisan make:command TaskEventGenerator
编辑命令类内容:

protected $signature = 'task:generate';
protected $description = '按预设间隔生成START/STOP任务事件';

public function handle()
{
    while (true) {
        $customTime = getCustomProgTime();
        $runSeconds = $customTime['run_seconds'];
        $progTime = $customTime['prog_time'];
        $actualTime = Carbon::now()->toDateTimeString();
        $actualTimeDisplay = Carbon::now()->format('h:i:sa');

        // 触发START事件:每10秒执行一次
        if ($runSeconds % 10 === 0) {
            $serverCount = rand(1, 5);
            $message = "Start {$serverCount} servers";
            TaskEvent::create([
                'prog_time' => $progTime,
                'event' => 'START',
                'message' => $message,
                'actual_time' => $actualTime,
                'display_message' => "{$progTime} - {$message}"
            ]);
        }

        // 触发STOP事件:每20秒执行一次
        if ($runSeconds % 20 === 0) {
            $serverCount = rand(1, 4);
            $message = "Stop {$serverCount} servers";
            TaskEvent::create([
                'prog_time' => $progTime,
                'event' => 'STOP',
                'message' => $message,
                'actual_time' => $actualTime,
                'display_message' => "{$progTime} - {$message}"
            ]);
        }

        // 休眠1秒避免重复执行
        sleep(1);
    }
}

4. 配置进程守护保证持续运行

使用Supervisor托管上述命令,保证应用运行时脚本持续执行,Supervisor配置参考:

[program:task-event-generator]
process_name=%(program_name)s_%(process_num)02d
command=php /你的项目绝对路径/artisan task:generate
autostart=true
autorestart=true
user=运行web服务的用户(比如www-data)
numprocs=1
redirect_stderr=true
stdout_logfile=/你的项目绝对路径/storage/logs/task_generator.log

配置完成后重启Supervisor即可生效。

5. 前端对接

现有JS时钟代码完全不需要修改,仅需新增接口从task_events表查询事件列表返回给前端渲染,和原有页面逻辑无缝兼容。

内容的提问来源于stack exchange,提问作者Daniel Kariuki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:42:02