我已经看到了一些关于如何在后台运行NSTask的好信息,尽管这并不完全是我想做的事情。我想做的是 定期 在后台运行NSTask(每30秒一次),然后杀死它;这可能是我想做的一个例子:
NSTask *theTask = [ [ NSTask alloc ] init ];
NSPipe *taskPipe = [ [ NSPipe alloc ] init ];
[ theTask setStandardError:taskPipe ];
[ theTask setStandardOutput:taskPipe ];
[ theTask setLaunchPath:@"/bin/ls" ];
[ theTask setArguments:[ NSArray arrayWithObject:@"-l" ] ];
[ theTask launch ];
// Wait 30 seconds, then repeat the task
答案 0 :(得分:2)
也许你可以简单地让线程睡眠并在do循环中等待30秒:
do {
[ theTask launch ]; //Launch the Task
sleep(30); //Sleep/wait 30 seconds
} while (someCondition);
否则您可以使用NSTimer:
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 30.0
target: self
selector:@selector(onTick:)
userInfo: nil repeats:YES];
- (void)onTick:(NSTimer *)timer {
//In this method that will be get called each 30 seconds,
//you have to put the action that you want to perform ...
[ theTask launch ];
}