Objective c 目标C,定期在后台运行NSTask
我已经看到了一些关于如何在后台运行NSTask的好信息,尽管这并不完全是我想要做的。我想做的是定期在后台运行一个NSTask(比如每30秒),然后杀死它;下面是我想做的一个例子:Objective c 目标C,定期在后台运行NSTask,objective-c,multithreading,nstask,Objective C,Multithreading,Nstask,我已经看到了一些关于如何在后台运行NSTask的好信息,尽管这并不完全是我想要做的。我想做的是定期在后台运行一个NSTask(比如每30秒),然后杀死它;下面是我想做的一个例子: NSTask *theTask = [ [ NSTask alloc ] init ]; NSPipe *taskPipe = [ [ NSPipe alloc ] init ]; [ theTask setStandardError:taskPipe ]; [ theTask setStandardOutput:t
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);
否则,您可以使用:
第一种方法简直令人无法忍受。如果你删除它,我会给你+1。我想我的问题的答案在这里:9年后,仍然在为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 ];
}