You may gain skill even failing an action; though, it can vary per skill.
Action time affects skill gain for most actions: The longer the action, the more skill you gain for that action. For example, a 20-second mining action will generally give the same amount of skill and characteristics as two 10-second mining actions. Lower stamina will increase the timer length.
If you gain skill with stamina at or near 0%, there is a massive penalty to the amount of skill gained for that action.
Nutrition also affects skill gain. When nutrition is higher than 50%, you get a bonus of 1% increased skill gain per 10% nutrition. For example, 65% nutrition would result in 1.5% extra skill gain, and 99% nutrition would result in 4.9% extra skill gain.