3

我已经看到了一些关于如何保持 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
4

1 回答 1

3

也许您可以简单地将线程置于睡眠状态并在 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 ];
}
于 2012-09-09T09:08:20.700 回答