Hello! I'm made a little perl script that runs as a service and does some stuff in the database every ten seconds but if for some reason it can not connect to the mysql db it dies. I would just want it to ignore the problem and try again next time. Please help! #!/usr/bin/perl # Perl modules use strict; use POSIX qw(setsid); use Mysql; # Flush the buffer $| = 1; # daemonize the program chdir '/' or die "Can't chdir to /: $!"; open STDIN, '/dev/null' or die "Can't read /dev/null: $!"; open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!"; open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!"; defined(my $pid = fork) or die "Can't fork: $!"; exit if $pid; setsid or die "Can't start a new session: $!"; umask 0; # Config variales my $host = "xxx"; my $database = "xxx"; my $user = "xxx"; my $pw = "xxx"; my $sql = "some SQL goes here"; while(1) { my $dbh = Mysql->connect($host, $database, $user, $pw); $dbh->query($sql); undef $dbh; #wait 10 seconds sleep(10); } Code (markup):
You might have better luck setting the script to run once and then setting it up as a cron job... although a cron job running every ten seconds could get annoying (or disabled by your host). You might also try some error trapping using 'eval'. Here's some untested changes to get you started on that route: while(1) { my $dbh; eval { $dbh = Mysql->connect($host, $database, $user, $pw) }; unless ($@) { # Execute query unless there is an error connecting to Mysql $dbh->query($sql); } undef $dbh; #wait 10 seconds sleep(10); } Code (markup): You can also add an 'else' clause and print '$@' to STDERR if you want to see why the db connection fails. (But this will fill up your error log if you have a lot of failed connections) Another way to do it would be to do a conditional and/or 'ref' test on the $dbh variable to ensure it points to a valid mysql connection. This would go after the connection attempt but before the query is executed. Hope this gives you some ideas. -Nitro