dispatch_timer_set_time.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2008-2011 Apple Inc. All rights reserved.
  3. *
  4. * @APPLE_APACHE_LICENSE_HEADER_START@
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * @APPLE_APACHE_LICENSE_HEADER_END@
  19. */
  20. #include <assert.h>
  21. #include <stdio.h>
  22. #include <string.h>
  23. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  24. #include <sys/time.h>
  25. #endif
  26. #include <dispatch/dispatch.h>
  27. #include <bsdtests.h>
  28. #include "dispatch_test.h"
  29. static void
  30. test_timer(void)
  31. {
  32. dispatch_test_start("Dispatch Update Timer");
  33. dispatch_queue_t main_q = dispatch_get_main_queue();
  34. //test_ptr("dispatch_get_main_queue", main_q, dispatch_get_current_queue());
  35. __block int i = 0;
  36. struct timeval start_time;
  37. gettimeofday(&start_time, NULL);
  38. dispatch_source_t s = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, main_q);
  39. test_ptr_notnull("dispatch_source_create", s);
  40. dispatch_source_set_timer(s, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), NSEC_PER_SEC, 0);
  41. dispatch_source_set_cancel_handler(s, ^{
  42. struct timeval end_time;
  43. gettimeofday(&end_time, NULL);
  44. // Make sure we actually managed to adjust the interval
  45. // duration. Fifteen one second ticks would blow past
  46. // this.
  47. test_long_less_than("total duration", end_time.tv_sec - start_time.tv_sec, 10);
  48. test_stop();
  49. dispatch_release(s);
  50. });
  51. dispatch_source_set_event_handler(s, ^{
  52. fprintf(stderr, "%d\n", ++i);
  53. if (i >= 15) {
  54. dispatch_source_cancel(s);
  55. } else if (i == 1) {
  56. dispatch_source_set_timer(s, dispatch_time(DISPATCH_TIME_NOW, 0), NSEC_PER_SEC / 10, 0);
  57. }
  58. });
  59. test_ptr_notnull("dispatch_source_timer_create", s);
  60. dispatch_resume(s);
  61. }
  62. int
  63. main(void) {
  64. test_timer();
  65. dispatch_main();
  66. return 0;
  67. }