In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "C language operation time function how to achieve regular execution of a task Mini Program", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "C language operation time function how to achieve regular execution of a task Mini Program" it!
Time Overview
As can be seen from the above picture:
1. You can get a value of type time_t from the kernel through the system call function time (), which is the calendar time, which is the number of seconds that have elapsed since the UTC time on January 1, 1970, from 00:00 0 to now. This time is also used to commemorate the birth of UNIX.
two。 The functions gmtime () and localtime () can convert the calendar time into a struct tm structure type variable. The current time information can be easily obtained through the members of the structure. We can also convert the variables of this type of structure into calendar time through the function mktime.
Struct tm {int tm_sec;/* seconds * / int tm_min; / * minutes * / int tm_hour;/* hours * / int tm_mday;/* date * / int tm_mon; / * months * / int tm_year; / * years since 1990 * / int tm_wday; / * weeks * / int tm_yday; / * days since January 1 this year * / int tm_isdst / * the flag of daylight saving time * /}
The 3.asctime () and ctime () functions produce a 26-byte string, which is similar to the system default output of the date command: Tue Feb 10 18:27:38 2020/n/0.
4.strftime () formats a struct tm structure as a string.
Common time functions and examples
1. Time function
Header file: time.h function definition: time_t time (time_t * t) description: returns the number of seconds that have elapsed since the UTC time of January 1, 1970, from 00:00 to now.
Examples are as follows:
# include # include int main () {time_t timep; long seconds = time (& timep); printf ("% ld\ n", seconds); printf ("% ld\ n", timep); return 0;}
Output:
Interested students can calculate how many seconds have been experienced since 00:00:00 on January 1, 1970.
Attachment: time_t traces the discovery from the long type through the continuous definition of typedef, # define.
2. Ctime function
Definition: char * ctime (const time_t * timep); description: convert the information in the time_t structure referred to by the parameter into a real-world time and date representation, and then return the result as a string. Note that this is local time.
Examples are as follows:
# include # include int main (void) {time_t timep; time (& timep); printf ("% s\ n", ctime (& timep)); return 0;}
Output:
3. Gmtime function
Definition: struct tm * gmtime (const time_t * timep); description: convert the information in the time_t structure referred to by the parameter timep into the real-world time and date representation, and then return the result from the structure tm. The time date returned by this function is UTC time without time zone conversion.
Examples are as follows:
# include # include int main (void) {char * wday [] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; time_t timep; struct tm * p; time (& timep); p = gmtime (& timep); printf ("% d/%d/%d", (1900 roomp-> tm_year), (1roomp-> tm_mon), p-> tm_mday) Printf ("% s% d:%d:%d\ n", WDayne [p-> tm_wday], p-> tm_hour,p- > tm_min,p- > tm_sec); return 0;}
Output:
4. Strftime function
# include definition: size_t strftime (char * s, size_t max, const char * format,const struct tm * tm). Note: similar to the snprintf function, we can output the information in the struct tm structure to the string pointed to by the s pointer according to the format string pointed to by format, up to a maximum of max bytes. Of course, the address pointed to by the s pointer needs to allocate space in advance, such as the character array or the heap space opened up by malloc. Among them, the detailed and exact representation of various dates and times of the format string is as follows, and we can format a variety of time strings as needed. Abbreviation of a day of the week A day of the week abbreviated% b full name of the month% c time string of the standard date% C first two digits of the year% d decimal representation of the day of the month% D month / day / year% e in the two character field The last two digits of the% F year-month-day% g year expressed in decimal system, using the week-based year% G year Number of minutes in decimal representation of month% m decimal system% minutes% n new line character% p local AM or PM equivalent display% r 12 hour hours Between% R display hours and minutes: hh:mm% S decimal seconds% t horizontal tab% T display minutes and seconds: hh:mm:ss% u the day ordinal of the week Monday is the week ordinal of the first day (values from 0 to 6, Monday is 0)% U, Sunday is the week ordinal of the first day (values from 0 to 53)% V, using the week-based annual% w decimal system (values from 0 to 6, Sunday is 0) the week ordinal of% W Take Monday as the first day (values from 0 to 53)% x standard date string% X standard time string% y without century decimal year (values from 0 to 99)% Y decimal year with century part of the decimal year% zzone% Z time zone name, if the time zone name cannot be obtained, an empty character is returned. % sign return value: returns the number of bytes of the s string after formatting if successful, excluding the null termination character, but the returned string includes the null byte termination character. Otherwise, the content of the returned 0mens string is undefined. It is worth noting that this started with later versions of libc4.4.4. For some older libc libraries, such as 4.4.1, the max value is returned if the given max is small. That is, the maximum number of bytes that a string can hold.
Examples are as follows:
1 # include 2 # include 3 4 # define BUFLEN 2555 int main (int argc, char * * argv) 6 {7 time_t t = time (0); 8 char tmpBuf [BUFLEN]; 9 10 strftime (tmpBuf, BUFLEN, "% Y%m%d%H%M%S", localtime (& t)) / / format date a 11 printf ("% s\ n", tmpBuf); 12 return 0; 13}
The implementation results are as follows:
The output indicates YYYYmmDDHHMMSS
5. Asctime function
Definition: char * asctime (const struct tm * timeptr); description: convert the information in the struct tm structure referred to by the parameter timeptr into the time and date representation used for real time, and the result is returned as a string. It differs from the ctime () function in that the parameters passed in are different structures. Return value: the UTC time is also returned.
Examples are as follows:
# include # include # include int main (void) {time_t timep; time (& timep); printf ("% s\ n", asctime (gmtime (& timep); return EXIT_SUCCESS;}
Output:
6. Localhost function
Struct tm * localhost (const time_t * timep); get the local current time and date
Examples are as follows:
# include # include # include int main (void) {char * wday [] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; time_t timep; struct tm * p; time (& timep); p = localtime (& timep); printf ("% d/%d/%d", (1900 roomp-> tm_year), (1roomp-> tm_mon), p-> tm_mday) Printf ("% s% d:%d:%d\ n", WDayne [p-> tm_wday], p-> tm_hour,p- > tm_min,p- > tm_sec); return EXIT_SUCCESS;}
Output:
7. Mktime function
Definition: time_t mktime (struct tm * timeptr); description: used to convert the tm structure data referred to in the parameter timeptr to the number of seconds that have elapsed since the UTC time on January 1, 1970, from 00:00 to now.
Examples are as follows:
# include # include # include int main (void) {time_t timep; struct tm * p; time (& timep); printf ("time ():% ld\ n", timep); p = localtime (& timep); timep = mktime (p); printf ("time ()-> localtime ()-> mktime ():% ld\ n", timep); return EXIT_SUCCESS;}
Output:
8. Gettimeofday function
Definition: int gettimeofday (struct timeval * tv,struct timezone * tz); description: the current time is returned from the structure referred to by tv, and the local time zone information is put into the structure referred to by tz
The structure timeval is defined as follows:
Struct timeval {long tv_sec; / * second * / long tv_usec; / * microsecond * /}
The structure timezone is defined as follows:
Struct timezone {how many minutes is the time difference between int tz_minuteswest; / * and greenwich * / int tz_dsttime; / * Daylight Saving time status * /}
Examples are as follows:
# include # include int main (void) {struct timeval tv; struct timezone tz; gettimeofday (& tv,&tz); printf ("tv_sec:% d\ n", tv.tv_sec); printf ("tv_usec:% d\ n", tv.tv_usec); printf ("tz_minuteswest:%d\ n", tz.tz_minuteswest); printf ("tz_dsttime:%d\ n", tz.tz_dsttime); return EXIT_SUCCESS;}
Output:
Comprehensive experiment
Now we use these time functions to implement a function that performs a task on a regular basis.
Function
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
The last modification time of the current log file should be recorded when the program is running.
Check whether the log file has been modified every 10 seconds, and hibernate for 10 seconds if it is not modified
If the log file is modified, copy the current log file into a backup file with the name of the backup file plus the current time
Send to ftp server via curl
Delete the backup file and repeat step 2.
The program flow chart is as follows:
Insert a picture description here
Introduction to function
Init ()
First record the current log file time and record it in the global variable last_mtime.
Check_file_change () reads the last modification time of the file and compares it with last_mtime. If it is the same, it returns 0 and the difference returns 1. 0.
File_name_add_time () copies the current log file into a backup file, with the name of the backup file plus the current time.
Stat ()
Get the attribute information of the corresponding file and store it in the struct stat structure variable.
Run the screenshot:
Step one:
Because the log file has not been modified, the program will not upload.
Step 2: manually enter the string yikoulinux into the log file t.log.
Step 3: print "file updated" because the file has changed, and you can see the log information of the file uploaded by curl.
The following is the root directory of the FTP server, and you can see the uploaded log file: tMoMo2020-7-26-1-19-45.log.
[supplement]
1. Configuration information, written directly in the code, should usually be read from the configuration file. This function is not added in this code for readers' convenience.
2.FTP server set up, this article is not described, there are many related documents, you can search on your own, you use File zilla
3. Usually this kind of program that needs to run for a long time needs to be set up as a daemon. This article does not add the corresponding function, the reader can search on its own. If you strongly request it, you can open a separate detailed introduction.
4. The management function of time in the code, please search the relevant articles by yourself.
5.curl also provides the related function library curl.lib, which can be used if you want to achieve more flexible functions.
The reason why the file is copied into a backup file first is to consider that other modules may modify the log file at any time to play a protective role.
The code is as follows
The code is as follows:
/ * Copyright (C) official account: linux * * * / # include # include typedef struct stat ST Unsigned long last_mtime; / * username and password is temporarily written and should actually be saved in the configuration file * / char name [32] = "user"; char pass [32] = "123456"; char ip [32] = "192.168.43.117"; char filename [32] = "t.log"; char dstfile [256] = {0}; int init (void) {/ / preparation structure ST status / call stat function int res = stat (filename,&status); if (- 1 = = res) {perror ("error:open file fail\ n"); return 0;} last_mtime = status.st_mtime; printf ("init time:%s\ n", ctime (& last_mtime)); return 1;} int check_file_change (void) {/ / preparation structure ST status / / call stat function int res = stat (filename,&status); if (- 1 = = res) {perror ("error:open file fail\ n"); return 0;} / / printf ("old:%s new:%s", ctime (& last_mtime), ctime (& status.st_mtime)); if (last_mtime = = status.st_mtime) {printf ("file not change\ n"); return 0;} else {printf ("file updated\ n") Last_mtime = status.st_mtime; return 1;}} void file_name_add_time (void) {ST status; time_t t; struct tm * tblock; char cmd [1024] = {0}; t = time (NULL); tblock = localtime (& t) Sprintf (dstfile, "t-%d-%d-%d-%d-%d-%d.log", tblock- > tm_year+1900, tblock- > tm_mon, tblock- > tm_mday, tblock- > tm_hour, tblock- > tm_min, tblock- > tm_sec); sprintf (cmd, "cp% s", filename,dstfile); / / printf ("cdm=%s\ n", cmd); system (cmd) } int main (void) {char cmd [1024] = {0}; init (); while (1) {if (check_file_change () = = 1) {file_name_add_time (); sprintf (cmd, "curl-u% s ftp://%s/-T% s", name,pass,ip,dstfile); / printf ("cdm=%s\ n", cmd); system (cmd); unlink (dstfile) } sleep (10);}} at this point, I believe you have a deeper understanding of "how to realize the C language operation time function to execute a task on a regular basis, Mini Program". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.