因此,我正在使用Java创建一个程序,该程序将在特定时间关闭应用程序并在特定时间允许它们。例如,游戏仅允许从下午5点到晚上7点。但我不知道如何制作它以便它在特定时间关闭,你只能在特定时间打开它。我有其余的代码,但没有时间的权限。 感谢您的帮助,
答案 0 :(得分:0)
您可以将TimerTask用于此目的。
示例:
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class ExitOn {
Timer timer = new Timer();
TimerTask exitApp = new TimerTask() {
@Override
public void run() {
System.exit(0);
}
};
public ExitOn() {
timer.schedule(exitApp, new Date(System.currentTimeMillis()+5*1000));//Exits after 5sec of starting the app
while(true)
System.out.println("hello");
}
public static void main(String[] args) {
new ExitOn();
}
}
答案 1 :(得分:0)
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test {
private static Scanner scanner;
public static void main(String[] args) throws Exception {
ScheduledExecutorService ex = Executors.newScheduledThreadPool(2);
ex.scheduleAtFixedRate(new Start(), 0 , 24, TimeUnit.HOURS);
ex.scheduleAtFixedRate(new End(), 2 , 24, TimeUnit.HOURS);
scanner = new Scanner(System.in);
while(true){
if(scanner.hasNext() && "Q".equals(scanner.next())){
System.exit(0);
}
Thread.sleep(10000);
}
}
}
class Start implements Runnable{
@Override
public void run() {
//start your game
}
}
class End implements Runnable{
@Override
public void run() {
//shutdown your game
}
}
正如jwenting所提到的,你也想要杀死或启动一个程序或只是改变游戏的许可。
这是在Windows中杀死进程的链接。希望它可以提供帮助。 How to find and kill running Win-Processes from within Java?
为了避免游戏开始,我还不知道。
java 7提供了更改文件权限的新功能。这可以帮助您在特殊时间设置文件的权限。
Path file = ...;
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-------");
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
try {
Attributes.setPosixFilePermissions(file, perms);
} catch (IOException x) {
System.err.println(x);
}