开发者

Is there a variable in Linux that shows me the last time the machine was turned on?

I want to create a script that,开发者_C百科 after knowing that my machine has been turned on for at least 7h, it does something.

Is this possible? Is there a system variable or something like that that shows me the last time the machine was turned on?


The following command placed in /etc/rc.local:

echo 'touch /tmp/test' | at -t $(date -d "+7 hours" +%m%d%H%M)

will create a job that will run a touch /tmp/test in seven hours.

To protect against frequent reboots and prevent adding multiple jobs you could use one at queue exclusively for this type of jobs (e.g. c queue). Adding -q c to the list of at parameters will place the job in the c queue. Before adding new job you can delete all jobs from c queue:

for job in $(atq -q c | sed 's/[ \t].*//'); do atrm $job; done


You can parse the output of uptime I suppose.


As Pavel and thkala point out below, this is not a robust solution. See their comments!

The uptime command shows you how long the system has been running.

To accomplish your task, you can make a script that first does sleep 25200 (25200 seconds = 7 hours), and then does something useful. Have this script run at startup, for example by adding it to /etc/rc.local. This is a better idea than polling the uptime command to see if the machine has been up for 7 hours (which is comparable to a kid in the backseat of a car asking "are we there yet?" :-))


Just wait for uptime to equal seven hours.

http://linux.die.net/man/1/uptime


I don't know if this is what you are looking for, but uptime command will give you for how many computer was running since last reboot.


$ cut -d ' ' -f 1 </proc/uptime

This will give you the current system uptime in seconds, in floating point format.

The following could be used in a bash script:

if [[ "$(cut -d . -f 1 </proc/uptime)" -gt "$(($HOURS * 3600))" ]]; then
...
fi


Add the following to your crontab:

@reboot sleep 7h; /path/to/job

Either /etc/crontab, /etc/cron.d/, or your users crontab, depending on whether you want to run it as root or the user -- don't forget to put "root" after "@reboot" if you put it in /etc/crontab or cron.d

This has the benefit that if you reboot multiple times, the jobs get cancelled at shut down, so you won't get a bunch of them stacking up if you reboot several times within 7 hours. The "@reboot" time specification triggers the job to be run once when the system is rebooted. "sleep 7h;" waits for 7 hours before running "/path/to/job".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜