How to periodically execute a function in C ??


 
Thread Tools Search this Thread
Top Forums Programming How to periodically execute a function in C ??
# 1  
Old 11-29-2007
Tools How to periodically execute a function in C ??

Hi,

I am looking for a C library feature, to which I can say execute a function every 10 seconds.

for Eg
Code:
#include <timer_lib.h>
fun1(){
      printf("I am still cool "); 
}

int main(){
   run(10,&fun1); // Should register & execute the function fun1 every 10 seconds
 return 0x0;
}

I am not interested in using the sleep function in a while loop or something..
Is there such a feature in the standard C library ??. I have heard about such facilities available on the kernel libraries.
# 2  
Old 11-29-2007
here is one shot,

register the function that has to be executed frequently as handler to the SIGALRM signal

and raise the alarm periodically
# 3  
Old 11-29-2007
I've seen the SIGALRM solution mentioned a few times, it's not good because it encourages heavyweight responses in signal handlers, as signals are asynchronous they can trash the heap if you are doing memory allocation/deallocation in the handler.

1. use a simple loop

Code:
while (1) {
     sleep(10);
     do_stuff();
}

2. do other stuff as well

Code:
while (1) {
      select with timeout
      if (time_is_ripe()) do_stuff();
}

3. use a callback from a library

Code:
XtAppAddTimeout(app,interval,do_stuff,data);

# 4  
Old 12-18-2007
Here's a C++ approach - it could be easily done in C

// chronistic.h
struct Chronistic
{
Chronistic(int _seconds) : seconds(_seconds) {next(time(0));}
virtual bool operator()() = 0; // pure virtural, never call from c'tor or d'tor
private: int seconds;
protected:
bool trigger()
{
time_t now = time(0);
if (now > trigger_target) return next(now); // always true
else return false;
}
private:
time_t trigger_target;
bool next(time_t now) // must not be virtual, must not call anything virtual (it's used in the c'tor). Always returns true.
{
trigger_target=now+seconds;
return true;
}
};


// chronistic.cpp
#include <iostream>
#include <cstdlib>

#include <string>
#include "chronistic.h"


using namespace std;


struct MyChronFunction : Chronistic
{
MyChronFunction(int seconds) : Chronistic(seconds) {}
virtual bool operator()()
{
if (!trigger()) return false;
cout<<"Time to do something"<<endl;
return true;
}
};


int main(int argc, char *argv[])
{
MyChronFunction cronologic(90); // setup to execute every 90 seconds
while (true)
{
cronologic();
usleep(10); // prevents race condition
}

return EXIT_SUCCESS;
}

Last edited by WebKruncher; 12-18-2007 at 10:38 PM.. Reason: typo
# 5  
Old 12-18-2007
That is awful

(a) nothing like using C++ to make a simple problem complicated.

(b) nothing like using C++ to obscure the fact that you have a truely terrible solution

You basically have a polling loop executing every 10 microseconds, when you should be telling the operating system the maximum time you are prepared to go to sleep for and let the OS put your task to sleep and get on and do other things.

If you have a list of tasks, you should find the earliest that something needs to be done then sleep until that time.
# 6  
Old 12-18-2007
to each his own

I like C++. Wasn't trying to do anything real fancy with the os, just a simple polling check might suffice.

Thanks for the feedback.
# 7  
Old 12-18-2007
Quote:
Originally Posted by WebKruncher
I like C++.
There is nothing wrong with using C++, but don't use it like a magician's sleight of hand to obscure a poor implementation.

Quote:
Originally Posted by WebKruncher
Thanks for the feedback.
No problem.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Execute function as soon as input is provided in menu drive shell script

Hi All, I have a menu driven scripts. As you know while running the script we have to input the option such as 1,2, and 3 to execute function accordingly. but after selecting the input we have to press Enter. My requirement is to execute function as soon as we press the option. Is there... (5 Replies)
Discussion started by: kiran_j
5 Replies

2. Shell Programming and Scripting

Need help to write a function in shell scripting to execute sql files

Hi, I am new to shell scripting and i need to write a automation script to execute sql files. I need to check the table if it is there in system tables and need to write a function to call the .sql files. For ex. I have a.sql,b.sql,c.sql files, where the sql file contains DELETE and INSERT... (1 Reply)
Discussion started by: Samah
1 Replies

3. Shell Programming and Scripting

Want to use function and execute the below query in script.

#!/bin/bash function getDeliveredDispatches(firstDateTime, lastDateTime, limit) { var cursor = db.dispatches.find( {$and: }} ]}, {"deliveryGroupId" : 1, "batchId": 1, "statusHistory.code" : 1} ); var wrongDispatchesIds = ; print("Number of dispatches selected based on filter = " +... (2 Replies)
Discussion started by: neel2462
2 Replies

4. Shell Programming and Scripting

MQ depth Periodically

Hi I am trying to a write a script which gives message queue depth for every 5 mins in a file. Commands that I use are runmqsc QM_Name display ql(*) curdepth Since I can use only MQSC commands I need help on how to fetch the output on to a file after executing display command. (3 Replies)
Discussion started by: jhilmil
3 Replies

5. Shell Programming and Scripting

Execute a function in background and then suspend it

Here is some back ground on the script. The script is to poll an arbitrary number of DB's. To do this I am creating a function that takes the file_path to the DB and the min poll interval as arguments. The function will be called for each DB and then ran in the background. The function I was... (6 Replies)
Discussion started by: ryandavison
6 Replies

6. UNIX for Dummies Questions & Answers

[ASK]execute shell with function in solaris

dear all i need your advice in shell with solaris i have testing script like this #!/usr/bin/bash function test(){ echo "testing only" } ## execute function ## test but if i running always got error like this test.sh: syntax error at line 1: `(' unexpected who can i running this... (7 Replies)
Discussion started by: zvtral
7 Replies

7. Shell Programming and Scripting

understand the function to execute

Gurus, Can you please tell me why this script is executing but i am getting no result...also can you tell me what is this gettime() doing? in a script i wrote this hour.SH -------------------------- gettime() { date '+%H' | { read hour TIME=${hour} } } : ----------------------... (2 Replies)
Discussion started by: RubinPat
2 Replies

8. UNIX for Advanced & Expert Users

Unable to execute a function using trap

I have a script A which calls script B. I wrote a function in script A to be executed when Kill command is issued for script A and I invoke that function using the trap command.The function identifies all child process running under script A (in this case script B) and kills the child process and... (3 Replies)
Discussion started by: smohandass
3 Replies

9. Shell Programming and Scripting

How to execute local function in awk

Hi All, Can you please tell me how to execute local function written in a shell script with awk. i tried with system command but its giving an error. (1 Reply)
Discussion started by: krishna_gnv
1 Replies

10. Shell Programming and Scripting

How can I execute own ksh function in find -exec

Hi, I wrote a smiple ksh function send_notification() { ... } and want to execute it on each file, matched by the find command. I tried: find / -name "*.err" -mtime -8 -exec send_notification {} \; but it doesn't work. What should I do? I work in ksh on Hp-Ux. Regards, Pit (11 Replies)
Discussion started by: piooooter
11 Replies
Login or Register to Ask a Question