sync_my.php
1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
//error_reporting();
include_once __DIR__."/../vendor/autoload.php";
swoole_set_process_name('php-email-sync-list-my');
function stop(){
    if(redis()->add('sync_my_pid_lock',getmypid(),10)){
        $keys =  redis()->keys('sync_my_pid:*');
        foreach ($keys as $key){
            list($k,$pid) = explode(':',$key);
            if(posix_kill($pid,0)){
                $t = redis()->get($key);
                if(time()-$t > 60){
                    _echo('向'.$pid.'发送终止信号');
                    if(posix_kill($pid,SIGTERM)){
                        redis()->delete($key);
                    }
                }
            }else{
                redis()->delete($key);
            }
        }
        redis()->delete('sync_my_pid_lock');
    }
}
\Co\run(function (){
    $goNum = 0;
    while (1){
        if($goNum>=50){
            co::sleep(1);
            continue;
        }
        $id = redis()->lPop('sync_email_lists_my');
        redis()->set('sync_my_pid:'.getmypid(),time(),86400);
        stop();
        // _echo('读取到'.$id);
        if($id && is_numeric($id)){
            // 占用当前的id,占用2小时
            if(redis()->add('just_sync_'.$id,time(),600)){
                go(function ($id) use (&$goNum){
                    $goNum++;
                    try{
                        // 开始同步
                        (new \Service\SyncMail($id))->sync();
                    }catch (Throwable $e){
                        _echo($e->getMessage());
                    }
                    co::defer(function () use ($id,&$goNum){
                        $goNum--;
                        // 30秒后 消除占用
                        redis()->expire('just_sync_'.$id,30);
                        \Lib\Log::getInstance()->write();
                    });
                },$id);
            }
        }else{
            co::sleep(1);
        }
    }
});