Skip to content

Instantly share code, notes, and snippets.

@puddingpimp
Last active December 19, 2015 03:59
Show Gist options
  • Save puddingpimp/5894377 to your computer and use it in GitHub Desktop.
Save puddingpimp/5894377 to your computer and use it in GitHub Desktop.
at timer - remove unused variable
// at - by Dave Cameron 2013
// A simple timer to run a job at a specific time (in the near future)
// compile like: gcc -Os at.c -o at -lrt
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <err.h>
#include <unistd.h>
int
wait_until(time_t a)
{
int r;
struct timespec req;
req.tv_sec = a;
req.tv_nsec = 0;
while(r = clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &req, 0) && r == EINTR);
return r;
}
int
at(int h, int m, int s)
{
struct tm lt;
time_t t, a;
time(&t);
localtime_r(&t, &lt);
if (h>lt.tm_hour ||
(h==lt.tm_hour && m>lt.tm_min)) {
// same day
lt.tm_hour = h;
lt.tm_min = m;
lt.tm_sec = s;
a = mktime(&lt);
} else {
// next day
lt.tm_hour = h;
lt.tm_min = m;
lt.tm_sec = s;
lt.tm_mday++;
a = mktime(&lt);
}
return wait_until(a);
}
void usage(char *arg0)
{
fprintf(stderr, "Usage: %s hh:mm[:ss] [action [args]]\n", arg0);
fprintf(stderr, "Waits until hh:mm[:ss] today or tomorrow to do action.\n");
exit(1);
}
int
main(int argc, char **argv)
{
int n, h, m, s;
if(argc<2) usage(argv[0]);
m=0; s=0;
n = sscanf(argv[1], "%d:%d:%d", &h,&m,&s);
if(n<2) {
errx(1, "invalid time");
}
if(argc==2) {
return at(h,m,s);
} else {
if(!at(h,m,s)) {
if(execvp(argv[2], argv + 2))
err(1, "couldn't exec %s", argv[2]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment