loop.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "hloop.h"
  2. #include "hbase.h"
  3. #include "nlog.h"
  4. void mylogger(int loglevel, const char* buf, int len) {
  5. if (loglevel >= LOG_LEVEL_ERROR) {
  6. stderr_logger(loglevel, buf, len);
  7. }
  8. if (loglevel >= LOG_LEVEL_INFO) {
  9. file_logger(loglevel, buf, len);
  10. }
  11. network_logger(loglevel, buf, len);
  12. }
  13. void on_idle(hidle_t* idle) {
  14. printf("on_idle: event_id=%lu\tpriority=%d\tuserdata=%ld\n", idle->event_id, idle->priority, (long)idle->userdata);
  15. }
  16. void on_timer(htimer_t* timer) {
  17. printf("on_timer: event_id=%lu\tpriority=%d\tuserdata=%ld\ttime=%lus\thrtime=%luus\n",
  18. timer->event_id, timer->priority, (long)timer->userdata, hloop_now(timer->loop), timer->loop->cur_hrtime);
  19. }
  20. void cron_hourly(htimer_t* timer) {
  21. time_t tt;
  22. time(&tt);
  23. printf("cron_hourly: %s\n", ctime(&tt));
  24. }
  25. void timer_write_log(htimer_t* timer) {
  26. static int cnt = 0;
  27. hlogd("[%d] Do you recv me?", ++cnt);
  28. hlogi("[%d] Do you recv me?", ++cnt);
  29. hloge("[%d] Do you recv me?", ++cnt);
  30. }
  31. void on_stdin(hio_t* io, void* buf, int readbytes) {
  32. printf("on_stdin fd=%d readbytes=%d\n", io->fd, readbytes);
  33. printf("> %s\n", buf);
  34. if (strncmp((char*)buf, "quit", 4) == 0) {
  35. hloop_stop(io->loop);
  36. }
  37. }
  38. int main() {
  39. // memcheck atexit
  40. MEMCHECK;
  41. hloop_t loop;
  42. hloop_init(&loop);
  43. // test idle and priority
  44. for (int i = HEVENT_LOWEST_PRIORITY; i <= HEVENT_HIGHEST_PRIORITY; ++i) {
  45. hidle_t* idle = hidle_add(&loop, on_idle, 10);
  46. idle->priority = i;
  47. }
  48. // test timer timeout
  49. for (int i = 1; i <= 10; ++i) {
  50. htimer_t* timer = htimer_add(&loop, on_timer, i*1000, 3);
  51. timer->userdata = (void*)i;
  52. }
  53. // test timer period
  54. int minute = time(NULL)%3600/60;
  55. htimer_add_period(&loop, cron_hourly, minute+1, -1, -1, -1, -1, INFINITE);
  56. // test network_logger
  57. htimer_add(&loop, timer_write_log, 1000, INFINITE);
  58. hlog_set_logger(mylogger);
  59. hlog_set_file("loop.log");
  60. nlog_listen(&loop, DEFAULT_LOG_PORT);
  61. // test nonblock stdin
  62. printf("input 'quit' to quit loop\n");
  63. char buf[64];
  64. hread(&loop, STDIN_FILENO, buf, sizeof(buf), on_stdin);
  65. hloop_run(&loop);
  66. return 0;
  67. }