libdispatch update
[platform/upstream/gcd.git] / dispatch-1.0 / testing / dispatch_timer_set_time.c
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
21 #include <sys/time.h>
22 #include <assert.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <sys/time.h>
26
27 #include <dispatch/dispatch.h>
28
29 #include <bsdtests.h>
30 #include "dispatch_test.h"
31
32 void
33 test_timer(void)
34 {
35         dispatch_test_start("Dispatch Update Timer");
36
37         dispatch_queue_t main_q = dispatch_get_main_queue();
38         //test_ptr("dispatch_get_main_queue", main_q, dispatch_get_current_queue());
39
40         __block int i = 0;
41         struct timeval start_time;
42
43         gettimeofday(&start_time, NULL);
44
45         dispatch_source_t s = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, main_q);
46         test_ptr_notnull("dispatch_source_create", s);
47
48         dispatch_source_set_timer(s, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), NSEC_PER_SEC, 0);
49
50         dispatch_source_set_cancel_handler(s, ^{
51                 struct timeval end_time;
52                 gettimeofday(&end_time, NULL);
53                 // Make sure we actually managed to adjust the interval
54                 // duration.  Seven one second ticks would blow past
55                 // this.
56                 test_long_less_than("total duration", end_time.tv_sec - start_time.tv_sec, 3);
57                 test_stop();
58
59                 dispatch_release(s);
60         });
61
62         dispatch_source_set_event_handler(s, ^{
63                 fprintf(stderr, "%d\n", ++i);
64                 if (i >= 7) {
65                         dispatch_source_cancel(s);
66                 } else if (i == 1) {
67                         dispatch_source_set_timer(s, dispatch_time(DISPATCH_TIME_NOW, 0), NSEC_PER_SEC / 10, 0);
68                 }
69         });
70         test_ptr_notnull("dispatch_source_timer_create", s);
71
72         dispatch_resume(s);
73 }
74
75 int
76 main(void) {
77         test_timer();
78         dispatch_main();
79
80         return 0;
81 }