Is it possible in C/C++ in Linux to get informed when a specified date/time is reached? - c++

Is it possible using standard C++ in Linux to get informed when a specified date/time is reached by the system time (assuming my process is up of course)?
I could just set a timer to the time I need to wait, but what happens if the user changes the system time? Can I get informed by the system that the user changed the system time to reset my timers?

The Linux kernel has such system calls, although, they are not integrated into the libc API.
You can create a timer, get a file descriptor for it from the kernel, and do a select or epoll call on the descriptor to be notified when the timer fires.
The man page for it: http://www.kernel.org/doc/man-pages/online/pages/man2/timerfd_create.2.html

Sure, just write code to do exactly what you want. For example: You could keep a list of all such timers, the date/time they're supposed to be fired, and what code should be executed when they occur. Then every so often you could check the time to see if it's past the time any of your timers should fire. If so, fire them, remove them from the list, and go on about your business.

See the documentation for 'at' command (man at)
For example, at could send you an email at a given time, like 2:35 PM.
at 14:35
warning: commands will be executed using /bin/sh
at> mail -s "It is 2:35 PM" dbadmin < /dev/null
at><EOT> # After CTRL/D pressed.
job 9 at Tue May 8 14:35:00 2012

You can calculate the time from program start to the event, and call
sleep (difftime-1);
Then you could control if the time was reset, but this way you would only be able to correct the time to the future - if the time was set back, you would have skipped the event.

Related

How to prevent procmail from crashing the platform and make it run one process at a time?

I have the problem that I capture emails and they arrive in masses, the issue is that every time they arrive in masses the platform crashes, the question is how to make it go running the process 1 at a time, is it possible? because currently I filled the entire procmail server where there were multiple processes at once, plus we add the executives who were working and the server died and we had to reboot and delete data from the procmail to get it working again.
Because once we capture the data it is working and making subprocesses.
This is the code:
SHELL = /bin/sh
LOGFILE = /var/log/procmail.log
LOGABSTRACT = "all"
VERBOSE = "on"
:0c
| php /srv/platform/laravel/artisan platform:catchemail >> /var/log/procmail_catchemail.log 2>&1
:0:
/var/log/plaform_catchemail
If by "platform" you mean the PHP script, you can serialize access to it by using a lock file.
:0c:.catchemail.lock
| php /srv/platform/laravel/artisan platform:catchemail >> /var/log/procmail_catchemail.log 2>&1
This means, if the file .catchemail.lock does not exist in your $MAILDIR, go ahead and create it, and hold it for the duration of this recipe.
If it does exist, sleep and try again.
There is a failure scenario if the lock is held for too long; Procmail's default behavior in this case is to bounce the message (i.e. cause the delivering MTA to regard it as undeliverable, and return an error message to the sender). You probably want to avoid that, ideally by telling the MTA to attempt delivery again at a later time. (The precise mechanism will depend on your MTA; but basically, by setting a suitable exit code.) But what's feasible and scalable ultimately depends on how many messages you receive vs how many you can process under this constraint.

How to specify a maximum amount of time a program can run in C++

In my C++ program, I will start other programs with exec. However, I want to be able to specify a maximum amount of time that the programs can run. How can that be done?
Is setrlimit the right thing to use?
Bit of a brute-force version, but... save/get the handle of the started programm/process, start a timer and kill the other process after the timer has expired?
2 solutions that comes to mind.
1- Send the duration to the second program via the command line and manage the duration internally in the 2nd exe.
2- Create a timer in the first exe and when the timer is triggered kill the 2nd process.
Max.
In general, it can't be done using standard c++ - you will have to use whatever scheduling functions your operating system (which you haven't specified) provides.

C++ What can I use instead sleep() function?

I'm building scrobbler, and I want my program to wait 10 seconds after song change, before scrobbling. I have been using sleep but I realized that if song change during these 10 seconds, program submit old song and get new one. I want If I change song, code start all over again.
I'm using Music Player Daemon (MPD) and libmpd to get songs' tags.
Note: program is under Unix.
It depens a lot on how your program works, but in principle, the easiest way would be to keep using sleep and check whether the user changed the song before sending out that data (after sleep has returned). So, instead of "try to sleep better", the goal would be "check that the data you send is really valid before sending".
A different possibility would be to wait on an epoll using either the timeout for sleeping or better yet on a timerfd, and notify song change via an eventfd. This has the advantage that it is "free" if you need reliable inter-thread communication and readiness notification anyway, which you most probably do (obviously you must have at least one additional GUI thread, or the user would not be able to change songs while you're blocking).
Damon's suggestion is a good one and may be a better overall design. If you're looking for something quick though, you could consider simply sending a signal to your application when the song changes. That will interrupt the sleep() system call and cause it to return early. Your application would then just need to handle the early return as appropriate. Depending on your implementation, this may not be appropriate but it might give you a quick fix.

Qt Get the amount of up time for current application

Is there a way in qt to get the up time of the application as well as the up time for the system?
Thanks in advance.
You can use the QElapsedTimer class from Qt 4.7 to get uptime for your app. This class will use monotonic clocks if it can.
Just create an instance, and call start on it at the start of your program. From then on, you can get the number of milliseconds your program has been running (or more precisely, since the call to start) by calling
myElapsedTimer.elapsed()
On Windows you can simply calculate by calling Winapi function to get process start datetime.
More information you can find at http://www.codeproject.com/KB/threads/ProcessTime.aspx
On Linux, you can use the times system call to tell you elapsed processor time. This will not count the time your program has been idle waiting for input, or blocked waiting for input, or the time that it's been preempted by other programs also running on the system. (Therefore, this makes it very good for benchmarks.)

Sleep Function Error In C

I have a file of data Dump, in with different timestamped data available, I get the time from timestamp and sleep my c thread for that time. But the problem is that The actual time difference is 10 second and the data which I receive at the receiving end is almost 14, 15 second delay. I am using window OS. Kindly guide me.
Sorry for my week English.
The sleep function will sleep for at least as long as the time you specify, but there is no guarantee that it won't sleep for longer.If you need an accurate interval, you will need to use some other mechanism.
If I understand well:
you have a thread that send data (through network ? what is the source of data ?)
you slow down sending rythm using sleep
the received data (at the other end of network) can be delayed much more (15 s instead of 10s)
If the above describe what you are doing, your design has several flaws:
sleep is very imprecise, it will wait at least n seconds, but it may be more (especially if your system is loaded by other running apps).
networks introduce a buffering delay, you have no guarantee that your data will be send immediately on the wire (usually it is not).
the trip itself introduce some delay (latency), if your protocol wait for ACK from the receiving end you should take that into account.
you should also consider time necessary to read/build/retrieve data to send and really send it over the wire. Depending of what you are doing it can be negligible or take several seconds...
If you give some more details it will be easier to diagnostic the source of the problem. sleep as you believe (it is indeed a really poor timer) or some other part of your system.
If your dump is large, I will bet that the additional time comes from reading data and sending it over the wire. You should mesure time consumed in the sending process (reading time before and after finishing sending).
If this is indeed the source of the additional time, you just have to remove that time from the next time to wait.
Example: Sending the previous block of data took 4s, the next block is 10s later, but as you allready consumed 4s, you just wait for 6s.
sleep is still a quite imprecise timer and obviously the above mechanism won't work if sending time is larger than delay between sendings, but you get the idea.
Correction sleep is not so bad in windows environment as it is in unixes. Accuracy of windows sleep is millisecond, accuracy of unix sleep is second. If you do not need high precision timing (and if network is involved high precision timing is out of reach anyway) sleep should be ok.
Any modern multitask OS's scheduler will not guarantee any exact timings to any user apps.
You can try to assign 'realtime' priority to your app some way, from a windows task manager for instance. And see if it helps.
Another solution is to implement a 'controlled' sleep, i.e. sleep a series of 500ms, checking current timestamp between them. so, if your all will sleep a 1s instead of 500ms at some step - you will notice it and not do additional sleep(500ms).
Try out a Multimedia Timer. It is about as accurate as you can get on a Windows system. There is a good article on CodeProject about them.
Sleep function can take longer than requested, but never less. Use winapi timer functions to get one function called-back in a interval from now.
You could also use the windows task scheduler, but that's going outside programmatic standalone options.