0% found this document useful (0 votes)
12 views2 pages

Example16 Lecture

The document contains two C programs: one for scheduling a task to execute at a specific time and another for measuring the time difference between two events. The first program uses a loop to check the current time and executes a task when the specified time is reached. The second program records the start and end times of a task to calculate and display the elapsed time.

Uploaded by

backy4u
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Example16 Lecture

The document contains two C programs: one for scheduling a task to execute at a specific time and another for measuring the time difference between two events. The first program uses a loop to check the current time and executes a task when the specified time is reached. The second program records the start and end times of a task to calculate and display the elapsed time.

Uploaded by

backy4u
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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 }

You might also like