Example: Scheduling a Task and
Measuring Time Difference
Your Name
March 17, 2025
1 Task Scheduler in C
This program waits until a specific time (e.g., [Link]) and then executes a task.
1 # include < stdio .h >
2 # include < time .h >
3 # include < unistd .h > // for sleep ()
4
5 void executeTask () {
6 printf ( " Task executed at the scheduled time !\ n " ) ;
7 }
8
9 int main () {
10 int target_hour = 14; // Set desired hour (24 - hour format )
11 int target_min = 30; // Set desired minute
12 int target_sec = 0; // Set desired second
13
14 while (1) {
15 time_t now = time ( NULL ) ; // Get current time
16 struct tm * current_time = localtime (& now ) ;
17
18 if ( current_time - > tm_hour == target_hour &&
19 current_time - > tm_min == target_min &&
20 current_time - > tm_sec == target_sec ) {
21 executeTask () ;
22 break ;
23 }
24 sleep (1) ; // Wait 1 second
25 }
26 return 0;
27 }
2 Measuring Time Difference Between Events
This program calculates the time elapsed between two events.
1
1 # include < stdio .h >
2 # include < time .h >
3
4 int main () {
5 time_t start_time , end_time ;
6 double elapsed ;
7
8 printf ( " Starting the task ...\ n " ) ;
9 start_time = time ( NULL ) ; // Record start time
10
11 for ( volatile long i = 0; i < 1000000000; i ++) ;
12
13 end_time = time ( NULL ) ; // Record end time
14 elapsed = difftime ( end_time , start_time ) ;
15
16 printf ( " Task completed in %.2 f seconds .\ n " , elapsed ) ;
17
18 return 0;
19 }