我看到了一些关于如何在后台运行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
也许你可以简单地让线程进入睡眠状态,并在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 ];
}