2017-06-28 8 views
0

macOS/iOSでタイマーを作成する方法を知りたい。 linuxではtime.hクラスのtimer_create()関数を使用して作成できますが、macOS/iOSではこの関数は存在しません。macOSでCタイマーを作成する

NSTimer(Objective-Cの)のようなもののC.

で何かあなたが睡眠のいくつかの組み合わせで、MacOSのためにpthreadsを使用することができますおかげ

+0

https://unix.stackexchange.com/questions/194480/why-is-timer-t-defined-in-time-h-on-linux-but-not-os-x –

+0

'getitimer'と' setitimer'を使います。 – jxh

+0

@JonnySchubertこの質問を投稿する前に、私はそのリンクを読んでいます。私の質問は解決しないでください。 –

答えて

0

Appleと話をした後、サポート:

ここで最も明白な候補はディスパッチタイマーソースです。

https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/dispatch_source_create.3.html

今、私は私が何か面白いものを見つけた場合は、タイマーのセクションを実装した後、私はそれについての詳細を投稿します、そのプロジェクトの他のセクションで働いています。

1

と時間

typedef struct Timer { 
     void (*fn)(void); 
     bool (*timer_delegate)(pthread_t, unsigned int, unsigned int); 
     unsigned int seconds; 
} Timer; 

void* timer_run(void *t) { 

    unsigned int start_time = time(NULL); 
    while(1) { 
     Timer tmr = *((Timer *) t); 
     bool should_kill_thread = tmr.timer_delegate(pthread_self(), start_time, time(NULL)); 
     if (should_kill_thread) pthread_cancel(pthread_self()); 
     tmr.fn(); 

     sleep(tmr.seconds); 
    } 
} 

bool should_kill_thread(pthread_t t, unsigned int start_time, unsigned int utime_new) { 
    printf("the start time was %d and the new time is %d \n", start_time, utime_new); 

    if (utime_new - start_time >= 9) { 
     return true; 
    } 

    return false; 
} 

void hello_world() { 
    printf("%s\n", "Hello, World!"); 
} 

int main(int argc, char const *argv[]) 
{ 
    pthread_t t1; 
    Timer args; 
    args.fn = &hello_world; 
    args.timer_delegate = should_kill_thread; 
    args.seconds = 1; // call every 1 second 

    int id = pthread_create(&t1, NULL, timer_run, &args); 
    if (id) { 
     printf("ERROR; return code from pthread_create() is %d\n", id); 
     exit(EXIT_FAILURE); 
    } 

    pthread_join(t1, NULL); // blocks main thread 
    printf("%s\n", "DONE"); // never reached until t1 is killed 
    return 0; 
} 
+0

あなたの答えをありがとう、しかし私はタイマーの車輪でそれを使用する必要があり、私は睡眠は私のプロジェクトでいくつかの制限があると思う。 –

関連する問題