001: /*
002: * @(#)schedule.java 1.2 04/12/06
003: *
004: * Copyright (c) 2004 Sun Microsystems, Inc. All Rights Reserved.
005: *
006: * See the file "LICENSE.txt" for information on usage and redistribution
007: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
008: */
009: package org.pnuts.lib;
010:
011: import pnuts.lang.*;
012: import java.io.*;
013: import java.util.*;
014:
015: public class schedule extends PnutsFunction {
016:
017: public schedule() {
018: super ("schedule");
019: }
020:
021: public boolean defined(int nargs) {
022: return nargs == 2 || nargs == 3;
023: }
024:
025: static Timer doSchedule(Date timeToRun, final PnutsFunction task,
026: final Context context) {
027: Timer timer = new Timer(true);
028: timer.schedule(new TimerTask() {
029: public void run() {
030: task.call(new Object[] {}, context);
031: }
032: }, timeToRun);
033: return timer;
034: }
035:
036: static Timer doSchedule(Date timeToRun, long period,
037: final PnutsFunction task, final Context context) {
038: Timer timer = new Timer(true);
039: timer.scheduleAtFixedRate(new TimerTask() {
040: public void run() {
041: task.call(new Object[] {}, context);
042: }
043: }, timeToRun, period);
044: return timer;
045: }
046:
047: public Object exec(Object[] args, Context context) {
048: int nargs = args.length;
049: switch (nargs) {
050: case 2: {
051: PnutsFunction task;
052: Object arg0 = args[0];
053: if (arg0 instanceof PnutsFunction) {
054: task = (PnutsFunction) arg0;
055: } else {
056: throw new IllegalArgumentException(String.valueOf(arg0));
057: }
058: Object arg1 = args[1];
059: Date timeToRun;
060: if (arg1 instanceof Date) {
061: timeToRun = (Date) arg1;
062: } else if (arg1 instanceof Number) {
063: timeToRun = new Date(System.currentTimeMillis()
064: + ((Number) arg1).longValue());
065: } else {
066: throw new IllegalArgumentException(String.valueOf(arg1));
067: }
068: return doSchedule(timeToRun, task, context);
069: }
070: case 3: {
071: Object arg0 = args[0];
072: PnutsFunction task;
073: if (arg0 instanceof PnutsFunction) {
074: task = (PnutsFunction) arg0;
075: } else {
076: throw new IllegalArgumentException(String.valueOf(arg0));
077: }
078: Object arg1 = args[1];
079: Date timeToRun;
080: if (arg1 instanceof Date) {
081: timeToRun = (Date) arg1;
082: } else if (arg1 instanceof Number) {
083: timeToRun = new Date(System.currentTimeMillis()
084: + ((Number) arg1).longValue());
085: } else {
086: throw new IllegalArgumentException(String.valueOf(arg1));
087: }
088: Object arg2 = args[2];
089: long period;
090: if (arg2 instanceof Number) {
091: period = ((Number) arg2).longValue();
092: } else {
093: throw new IllegalArgumentException(String.valueOf(arg2));
094: }
095: return doSchedule(timeToRun, period, task, context);
096: }
097: default:
098: undefined(args, context);
099: return null;
100: }
101: }
102:
103: public String toString() {
104: return "function schedule(task(), timeToRun {, period})";
105: }
106: }
|