代码之家  ›  专栏  ›  技术社区  ›  vehomzzz

如何模拟cron作业

  •  12
  • vehomzzz  · 技术社区  · 14 年前

    我在考虑使用无限while循环,睡眠24小时,检查是否是周末,如果是,执行脚本。

    linux上bash下的好解决方案是什么?

    我当前的实现:

    #! /bin/bash
    
     while [ true ]; do
        if [[ $(date +%u) -lt 6 ]]; then
                   ./program
            else
                 echo Today is a weekend, processing is skipped. Back to sleep.
        fi
        sleep  86400
    done
    

    5 回复  |  直到 14 年前
        1
  •  11
  •   camh    14 年前

    在没有每个用户crontab的时候,我经常使用at(1)来完成这个任务。

    #!/bin/sh
    ... do stuff...
    at -f /path/to/me 5pm tomorrow
    

    我不认为你可以指定一个timespec为“nextweekend”,所以如果不是周末的话,你只需要重新安排每天的时间,让你的脚本退出(在安排下一个at作业之后)。

    编辑:或者不是每天都安排,而是找出今天是什么,并适当地安排。例如

    day=Saturday
    if [ $(date +%u) -eq 6 ] ; then day=Sunday ; fi
    at -f /path/to/me 5pm next $day
    

    如果此脚本在星期六运行,它会将下一次运行安排为下星期天,否则将在下星期六运行。 [ $(date +%A) = Saturday ]

        2
  •  5
  •   AndyG    7 年前

    对于Perl解决方案,请看 Schedule::Cron

    use 5.012;
    use warnings;
    use Schedule::Cron;
    
    my $cron = Schedule::Cron->new( sub {} );
    
    # add weekend run @ 05:00 
    $cron->add_entry('0 5 * * Sat,Sun', sub {
        system './program';
    });
    
    $cron->run();
    
        3
  •  1
  •   Ven'Tatsu    14 年前

    假设您真的不能使用cron或at来调度作业,您将需要编写一个sleep循环。如何编写的细节将根据您的要求而有所不同。

    如果你只想一天执行一次,你就得担心睡眠不足。大多数语言的sleep函数下面的sleep系统调用并不能保证它将按照请求的时间长度进行睡眠。您的程序可能会比要求的睡眠时间稍长或短得多。你可以安排24小时的睡眠,但操作系统可能会在几个小时后甚至几秒钟后唤醒你的程序来发送信号。如果您没有跟踪上一次跑步或下一次预期跑步,您可以每天执行多次。

    你需要考虑夏令时/夏令时。一年的某一天有23个小时,另一天有25个小时。

    set next_time_to_run
    loop forever
        sleep time_difference_in_seconds(current_time, next_time_to_run)
        if current_time is close to next_time_to_run
            execute code
            update next_time_to_run
        end if
    end loop
    
        4
  •  1
  •   Dennis Williamson    14 年前

    使用长的 sleep 你的程序对时间的想法会改变。最好是用短句循环 睡觉

    如果你的管理员不允许你使用 cron ,他们可能不高兴你绕过了限制。

    不过,这里有一个大致的轮廓:

    while :
    do
        dow=$(date +%u)
        if (( dow == 6 || dow == 7 ))
        # you can check a flag or counter to limit the number of times it's performed
        # or use a more refined date spec than just whole days (times of day, in other words)
        then
            do_something
            sleep 1h    # or use a smaller or larger interval
        fi
    done
    
        5
  •  0
  •   Alexandr Ciornii    14 年前

    你可以用 snaked . 它类似于cron,但是是用Perl编写的。