Here is the syntax to optimize all databases from your command line:
mysqlcheck --all-databases --optimize --user=USER --password=PASSWORD
And here are the chron settings for daily optimize:
0 4 * * *
mysqlcheck --all-databases --optimize --user=USER --password=PASSWORD
if you also want to repair and check the tables (I don’t recommend this), then here is the syntax:
mysqlcheck --all-databases --optimize --auto-repair --user=USER --password=PASSWORD