Skip to content

Instantly share code, notes, and snippets.

@ShonFrazier
Last active December 20, 2015 03:18
Show Gist options
  • Save ShonFrazier/6062238 to your computer and use it in GitHub Desktop.
Save ShonFrazier/6062238 to your computer and use it in GitHub Desktop.
dispatch timer
//
// dispatch-timer.c
//
// Created by Shon Frazier on 4/22/13.
// Copyright (c) 2013 Shon Frazier. All rights reserved.
//
#include <stdio.h>
#include <dispatch/dispatch.h>
#define FREQ (1000.)
int main(int argc, const char * argv[])
{
__block uint64_t count = 0;
uint64_t interval = (1./FREQ) * NSEC_PER_SEC;
uint64_t leeway = 0.5 * NSEC_PER_SEC;
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 0);
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_event_handler(timer, ^{
if(!(count % (uint64_t)FREQ)) fprintf(stdout, "%lli\n", count);
fflush(stdout);
count ++;
});
dispatch_source_set_timer(timer, start, interval, leeway);
dispatch_resume(timer);
dispatch_main();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment