You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.5KB

  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include <csignal>
  11. #include <iostream>
  12. #include "Util/util.h"
  13. #include "Util/logger.h"
  14. #include "Util/TimeTicker.h"
  15. #include "Util/onceToken.h"
  16. #include "Poller/EventPoller.h"
  17. using namespace std;
  18. using namespace toolkit;
  19. int main() {
  20. //设置日志
  21. Logger::Instance().add(std::make_shared<ConsoleChannel>());
  22. Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());
  23. Ticker ticker0;
  24. int nextDelay0 = 50;
  25. std::shared_ptr<onceToken> token0 = std::make_shared<onceToken>(nullptr,[](){
  26. TraceL << "task 0 被取消,可以立即触发释放lambad表达式捕获的变量!";
  27. });
  28. auto tag0 = EventPollerPool::Instance().getPoller()->doDelayTask(nextDelay0, [&,token0]() {
  29. TraceL << "task 0(固定延时重复任务),预期休眠时间 :" << nextDelay0 << " 实际休眠时间" << ticker0.elapsedTime();
  30. ticker0.resetTime();
  31. return nextDelay0;
  32. });
  33. token0 = nullptr;
  34. Ticker ticker1;
  35. int nextDelay1 = 50;
  36. auto tag1 = EventPollerPool::Instance().getPoller()->doDelayTask(nextDelay1, [&]() {
  37. DebugL << "task 1(可变延时重复任务),预期休眠时间 :" << nextDelay1 << " 实际休眠时间" << ticker1.elapsedTime();
  38. ticker1.resetTime();
  39. nextDelay1 += 1;
  40. return nextDelay1;
  41. });
  42. Ticker ticker2;
  43. int nextDelay2 = 3000;
  44. auto tag2 = EventPollerPool::Instance().getPoller()->doDelayTask(nextDelay2, [&]() {
  45. InfoL << "task 2(单次延时任务),预期休眠时间 :" << nextDelay2 << " 实际休眠时间" << ticker2.elapsedTime();
  46. return 0;
  47. });
  48. Ticker ticker3;
  49. int nextDelay3 = 50;
  50. auto tag3 = EventPollerPool::Instance().getPoller()->doDelayTask(nextDelay3, [&]() -> uint64_t {
  51. throw std::runtime_error("task 2(测试延时任务中抛异常,将导致不再继续该延时任务)");
  52. });
  53. sleep(2);
  54. tag0->cancel();
  55. tag1->cancel();
  56. WarnL << "取消task 0、1";
  57. //退出程序事件处理
  58. static semaphore sem;
  59. signal(SIGINT, [](int) { sem.post(); });// 设置退出信号
  60. sem.wait();
  61. return 0;
  62. }