该代码在myeclipse8.5测试通过:
import java.io.IOException;import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;
import java.awt.event.*;
import javax.swing.*;
public class CtrWDS extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JButton restart,shutdown,logout;
Box boxh;
private CtrWDS(String s) {
super(s);
restart=new JButton("重起");
shutdown=new JButton("关机");
logout=new JButton("注销");
boxh=Box.createHorizontalBox();
restart.addActionListener(this);
shutdown.addActionListener(this);
logout.addActionListener(this);
boxh.add(restart);
boxh.add(shutdown);
boxh.add(logout);
add(boxh);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void exec(String kind) {
try {
Runtime.getRuntime().exec("cmd /c start call shutdown -"+kind+" -f -t 60");
}
catch (IOException e) {
System.out.println("执行失败");
}
}
public void shutdown() {
exec("S");
}
public void restart() {
exec("R");
}
public void logout() {
exec("L");
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==shutdown)
{
shutdown();
}
else if(e.getSource()==restart)
{
restart();
}
else if(e.getSource()==logout)
{
logout();
}
}
@SuppressWarnings("deprecation")
public static void main(String[] str) {
java.util.Timer timer = new java.util.Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// 获取系统时间
// 如果是星期六早上9点,关闭计算机
Date now = new Date();
if ("星期六".equals(getWeekOfDate(now)) || "星期日".equals(getWeekOfDate(now)) && now.getHours() > 9) {
CtrWDS ctr = new CtrWDS("关机控制");
ctr.exec("s");
}
}
}, 10 * 1000, 20 * 60 * 1000);
}
/**
* 获取当前日期是星期几<br>
*
* @param dt
* @return 当前日期是星期几
*/
public static String getWeekOfDate(Date dt) {
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
}