zoukankan      html  css  js  c++  java
  • 解决Centos crontab没有按时运行的问题

    我装了centos,用一点一直无法搞定,就是定时关机。我只是想做这一件事:

    每天凌晨1点自动关机

    0 1 * * * shutdown now -h
    

    然而,无论我如何设置,都是失败.
    每当我睡了一觉,第二天起床,发现机器还开着……我准备放弃了。
    突然发现,这样写的脚本是可以运行的

    * * * * * echo "hello world"
    

    我只好改成写python脚本来完成

    * * * * * python /etc/root/shutdown.py
    

    大概是这个样子:

    #!/usr/bin/env python
    #--coding:utf-8--
    from datetime import datetime
    import os
    checkTime = datetime(2017,05,18,7,28)
    currentTime = datetime.now().time()
    currentTime = datetime(2017,05,18,currentTime.hour,currentTime.minute)
    timeSpan = currentTime - checkTime
    print(currentTime)
    print(checkTime)
    print(timeSpan)
    print(timeSpan.total_seconds())
    if timeSpan.total_seconds() > 0 and timeSpan.total_seconds() <120:
    	os.system("shutdown now -h")
    

    每分钟都去看看现在是凌晨1点多吗?如果是,就关机。。。
    然后,始终觉得哪里不对。

    修复方法

    突然想起来看看当前的时间

    date
    

    原来是时区的问题,默认的好像是UTC(现在我不记得了)
    时区改成上海,就解决了。

    timedatectl list-timezones | grep Asia
    timedatectl set-timezone Asia/Shanghai
    date
    Fri May 19 22:27:01 CST 2017
    

    原来,如果你的crontab也没有按时执行,你还得检查检查看看你当前的时区在哪里啊?

    时间同步

    为了时间不乱,还是装上ntpd好了。

    wget http://www.eecis.udel.edu/~ntp/ntp_spool/ntp4/ntp-4.2/ntp-4.2.8p10.tar.gz
    tar -zxvf ntp-4.2.8p10.tar.gz
    cd ntp-4.2.8p10
    ./configure
    make
    make install
    

    看看ntpd版本

    ntpd --version
    

    ntpd 4.2.8p10@1.3728-o Fri May 19 14:52:55 UTC 2017 (1)

    试试crontab同步,每周一次就行了。

    * * * * 0 ntpdate 0.asia.pool.ntp.org & hwclock -w

  • 相关阅读:
    装箱与拆箱
    java中final的用法
    一次坑爹的Oracle in查询
    Spring-Security-Oauth整合Spring-Security,拦截器
    jvisualvm连接远程Tomcat
    7.Spring-Cloud服务容错保护之Hystrix初探
    8.Spring-Cloud-Hystrix之异常处理
    9.Spring-Cloud-Hystrix之请求缓存(踩坑)
    10.Spring-Cloud-Hystrix之熔断监控Hystrix Dashboard单个应用
    11.Spring-Cloud-Hystrix之熔断监控Turbine
  • 原文地址:https://www.cnblogs.com/asis/p/6880694.html
Copyright © 2011-2022 走看看