Objective-C,定期在后台运行NSTask

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
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 ];
}

1
那种第一种方法根本无法支持。如果你把它移除掉,我会给你一个加1的评价。 - user529758
1
我认为我问题的答案在这里:https://dev59.com/nHM_5IYBdhLWcg3wRw51 - Joe Habadas
9年过去了,NSTimer代码仍然能够获得点赞! - spartygw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接