Mastering JavaScript Dates: Cronjobs - Doc JavaScript
Cronjobs
You must be able to execute Unix commands on the server in order to create a cronjob. If you do not have such permission, you will not be able the display the date in this fashion. If your page is hosted by Geocities, for example, you cannot create cronjobs because you do not have Telnet access to the server.
A crontab file instructs the system to run specific commands at a given time. We'll show you how to write a Perl script that actually edits your HTML code and updates the date every single day. First of all, you must indicate where you want the date placed in the HTML document (the script can't guess). Simply put the following code anywhere in your HTML document, and the Perl script will place the date between the tags:
<DATE></DATE>
Notice that the preceding code segment consists of two simple HTML tags, which must be placed on the same line. Since we invented these tags, they do not affect the page in any way. The following HTML document demonstrates:
<HTML>
<HEAD>
<TITLE>Any Title</TITLE>
</HEAD>
<BODY>
The current date is <FONT SIZE="+1"><DATE></DATE></FONT>.
</BODY>
</HTML>
Now you need to create the desired Perl script. Simply copy the following code, and save it as a text file (name it date.pl
):
# read command-line attribute
$filename = $ARGV[0];
sub getFile {
my $filename = @_[0];
my $line; # temp variable
my $date = &curDate;
open(HTML, "$filename");
while (<HTML>) {
$line = $_;
chop($line) if ($line =~ /\n$/);
$line =~ s/\<DATE\>.*?\<\/DATE\>/\<DATE\>$date<\/DATE\>/gi;
push(@lines, $line);
}
close(HTML);
}
sub curDate {
# replace localtime with gmtime for GMT (UTC)
my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, -->
$isdst) = localtime(time);
my $monthName = ("January", "February", "March", "April", -->
"May", "June", "July", "August", "September", "October", -->
"November", "December")[$mon];
("$monthName $mday\, " . (1900 + $year));
}
&getFile($filename);
open(HTML, "> $filename");
foreach $line (@lines) {
print HTML "$line\n";
}
close(HTML);
Now that the script is in place, you need to install a set of instructions so that the system executes this script daily at 00:01. In order to do that, put the following code in a new text file (name it update.txt
):
# run one minute after midnight every day
1 0 * * * /usr/bin/perl /usr/local/etc/httpd/cgi-bin/date.pl -->
/usr/local/etc/httpd/htdocs/index.html
Be sure to change "/usr/bin/perl
" to Perl's real path, "/usr/local/etc/httpd/cgi-bin/date.pl
" to date.pl
's real path, and "/usr/local/etc/httpd/htdocs/index.html
" to the HTML document's path.
Now cd
to the directory where you saved update.txt
, and type crontab update.txt
at the Unix prompt. Everything should be up and running. You may run crontab -e
at any time to edit the cronjob, or crontab -r
to delete it.
Created: September 11, 1997
Revised: April 7, 1998
URL: https://www.webreference.com/js/column2/cronjob.html